]> de.git.xonotic.org Git - xonotic/netradiant.git/blob - radiant/texwindow.cpp
* fixed a lot of compiler warnings (mostly const char * stuff and use of uninitialize...
[xonotic/netradiant.git] / radiant / texwindow.cpp
1 /*
2 Copyright (C) 1999-2007 id Software, Inc. and contributors.
3 For a list of contributors, see the accompanying CONTRIBUTORS file.
4
5 This file is part of GtkRadiant.
6
7 GtkRadiant is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12 GtkRadiant is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GtkRadiant; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20 */
21
22 //
23 // Texture Window
24 //
25 // Leonardo Zide (leo@lokigames.com)
26 //
27
28 /*!\todo
29 Clean up texture menu.
30 - Remove all global variables and use some objects instead.
31 - Create an interface for a plugin to add texture menu items.
32 - Make sure the interface is not dependent on gtk.
33 */
34
35 #ifdef _WIN32
36 //#include <gdk/win32/gdkwin32.h>
37 #include <gdk/gdkwin32.h>
38 #endif
39 #if defined (__linux__) || defined (__APPLE__)
40 #include <gdk/gdkx.h>
41 #include <dirent.h>
42 #endif
43 #include <gtk/gtk.h>
44 #include <glib/gi18n.h>
45 #include <assert.h>
46 #include <sys/stat.h>
47 #include "stdafx.h"
48 #include "texwindow.h"
49 #include "str.h"
50 #include "missing.h"
51 #include "texmanip.h"
52
53 #define TYP_MIPTEX      68
54 static unsigned tex_palette[256];
55
56 #define FONT_HEIGHT     10
57
58 //int           texture_mode = GL_NEAREST;
59 //int           texture_mode = GL_NEAREST_MIPMAP_NEAREST;
60 //int           texture_mode = GL_NEAREST_MIPMAP_LINEAR;
61 //int           texture_mode = GL_LINEAR;
62 //int           texture_mode = GL_LINEAR_MIPMAP_NEAREST;
63 int             texture_mode = GL_LINEAR_MIPMAP_LINEAR;
64
65 int g_nTextureOffset = 0;
66
67 // current active texture directory
68 //++timo FIXME: I'm not sure this is used anymore
69 char            texture_directory[128];
70 // if true, the texture window will only display in-use shaders
71 // if false, all the shaders in memory are displayed
72 qboolean g_bShowAllShaders;
73
74 bool g_bFilterEnabled = false;
75 CString g_strFilter;
76
77 // texture layout functions
78 // TTimo: now based on shaders
79 int     nActiveShadersCount;
80 int     nCurrentShader;
81 IShader*  pCurrentShader;
82 qtexture_t  *current_texture = NULL;
83 int     current_x, current_y, current_row;
84
85 // globals for textures
86 int     texture_nummenus;
87 char    texture_menunames[MAX_TEXTUREDIRS][128];
88
89 // the list of scripts/*.shader files we need to work with
90 // those are listed in shaderlist file
91 // FIXME TTimo I get the feeling that those would need to move to the shaders module
92 //   for now it's still more simple to just keep it here
93 GSList *l_shaderfiles = NULL;
94
95 void SelectTexture (int mx, int my, bool bShift, bool bFitScale=false);
96
97 void  Texture_MouseDown (int x, int y, int buttons);
98 void  Texture_MouseMoved (int x, int y, int buttons);
99
100 CPtrArray g_lstSkinCache;
101
102 // TTimo: modifed to add a qtexture_t, Texture_LoadSkin loads using the shader API / QERApp_TryTexture_ForName
103 // m_strName is a copy of qtex->name
104 struct SkinInfo
105 {
106   CString m_strName;
107   int m_nTextureBind;
108   qtexture_t *m_qtex;
109   SkinInfo(const char *pName, int n, qtexture_t *qtex)
110   {
111     m_strName = pName;
112     m_nTextureBind = n;
113     m_qtex = qtex;
114   };
115   SkinInfo(){};
116 };
117
118 // =============================================================================
119 // global functions
120
121 // gets active texture extension
122 //
123 // FIXME: fix this to be generic from project file
124 //
125 int GetTextureExtensionCount()
126 {
127   // hardcoded hack for png support
128   if (g_pGameDescription->mGameFile == "sof2.game")
129     return 3;
130   else
131     return 2;
132 }
133
134 const char* GetTextureExtension(int nIndex)
135 {
136   switch(nIndex)
137   {
138     case 0:
139       return "tga";
140       break;
141     case 1:
142       return "jpg";
143       break;
144     case 2:
145       return "png";
146       break;
147     default:
148       return NULL;
149   }
150 }
151
152 /*
153 ==============
154 Texture_InitPalette
155 ==============
156 */
157 void Texture_InitPalette (byte *pal)
158 {
159   int   r,g,b;
160   int   i;
161   int   inf;
162   byte  gammatable[256];
163   float gamma;
164
165   gamma = g_qeglobals.d_savedinfo.fGamma;
166
167   if (gamma == 1.0)
168   {
169     for (i=0 ; i<256 ; i++)
170       gammatable[i] = i;
171   } else
172   {
173     for (i=0 ; i<256 ; i++)
174     {
175       inf = (int)( 255.0f * pow( ( i + 0.5f ) / 255.5f , gamma ) + 0.5f );
176       if (inf < 0)
177         inf = 0;
178       if (inf > 255)
179         inf = 255;
180       gammatable[i] = inf;
181     }
182   }
183
184   for (i=0 ; i<256 ; i++)
185   {
186     r = gammatable[pal[0]];
187     g = gammatable[pal[1]];
188     b = gammatable[pal[2]];
189     pal += 3;
190
191     //v = (r<<24) + (g<<16) + (b<<8) + 255;
192     //v = BigLong (v);
193
194     //tex_palette[i] = v;
195     tex_palette[i*3+0] = r;
196     tex_palette[i*3+1] = g;
197     tex_palette[i*3+2] = b;
198   }
199 }
200
201 void SetTexParameters (void)
202 {
203   qglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, texture_mode );
204
205   switch ( texture_mode )
206   {
207   case GL_NEAREST:
208   case GL_NEAREST_MIPMAP_NEAREST:
209   case GL_NEAREST_MIPMAP_LINEAR:
210     qglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
211     break;
212   case GL_LINEAR:
213   case GL_LINEAR_MIPMAP_NEAREST:
214   case GL_LINEAR_MIPMAP_LINEAR:
215     qglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
216     break;
217   }
218 }
219
220 /*
221 ============
222 Texture_SetMode
223 ============
224 */
225 void Texture_SetMode(int iMenu)
226 {
227   int iMode;
228   qboolean texturing = true;
229   gpointer item = NULL;
230
231   switch (iMenu)
232   {
233   case ID_VIEW_NEAREST:
234     item = g_object_get_data (G_OBJECT (g_pParentWnd->m_pWidget), "menu_view_nearest");
235     iMode = GL_NEAREST;
236     break;
237   case ID_VIEW_NEARESTMIPMAP:
238     item = g_object_get_data (G_OBJECT (g_pParentWnd->m_pWidget), "menu_view_nearestmipmap");
239     iMode = GL_NEAREST_MIPMAP_NEAREST;
240     break;
241   case ID_VIEW_LINEAR:
242     item = g_object_get_data (G_OBJECT (g_pParentWnd->m_pWidget), "menu_view_linear");
243     iMode = GL_LINEAR;
244     break;
245   case ID_VIEW_BILINEAR:
246     item = g_object_get_data (G_OBJECT (g_pParentWnd->m_pWidget), "menu_view_bilinear");
247     iMode = GL_NEAREST_MIPMAP_LINEAR;
248     break;
249   case ID_VIEW_BILINEARMIPMAP:
250     item = g_object_get_data (G_OBJECT (g_pParentWnd->m_pWidget), "menu_view_bilinearmipmap");
251     iMode = GL_LINEAR_MIPMAP_NEAREST;
252     break;
253   case ID_VIEW_TRILINEAR:
254     item = g_object_get_data (G_OBJECT (g_pParentWnd->m_pWidget), "menu_view_trilinear");
255     iMode = GL_LINEAR_MIPMAP_LINEAR;
256     break;
257   case ID_TEXTURES_WIREFRAME:
258     item = g_object_get_data (G_OBJECT (g_pParentWnd->m_pWidget), "menu_view_wireframe");
259     iMode = -1;
260     texturing = false;
261     break;
262   case ID_TEXTURES_FLATSHADE:
263     item = g_object_get_data (G_OBJECT (g_pParentWnd->m_pWidget), "menu_view_flatshade");
264     iMode = -1;
265     texturing = false;
266     break;
267   }
268
269   g_qeglobals.d_savedinfo.iTexMenu = iMenu;
270   // NOTE: texture_mode is a GLenum used directly in glTexParameter
271   if(iMode!=-1) texture_mode = iMode;
272
273   g_bIgnoreCommands++;
274   if (item != NULL)
275     gtk_check_menu_item_set_active (GTK_CHECK_MENU_ITEM (item), TRUE);
276   g_bIgnoreCommands--;
277
278   if (texturing)
279     SetTexParameters ();
280
281   if ( !texturing && iMenu == ID_TEXTURES_WIREFRAME)
282   {
283     g_pParentWnd->GetCamWnd()->Camera()->draw_mode = cd_wire;
284     Map_BuildBrushData();
285     Sys_UpdateWindows (W_ALL);
286     return;
287   } else if ( !texturing && iMenu == ID_TEXTURES_FLATSHADE)
288   {
289     g_pParentWnd->GetCamWnd()->Camera()->draw_mode = cd_solid;
290     Map_BuildBrushData();
291     Sys_UpdateWindows (W_ALL);
292     return;
293   }
294
295   for (qtexture_t *q = g_qeglobals.d_qtextures; q; q = q->next)
296   {
297     qglBindTexture (GL_TEXTURE_2D, q->texture_number);
298     SetTexParameters ();
299   }
300
301   // select the default texture
302   qglBindTexture( GL_TEXTURE_2D, 0 );
303
304   qglFinish();
305
306   if (g_pParentWnd->GetCamWnd()->Camera()->draw_mode != cd_texture)
307   {
308     g_pParentWnd->GetCamWnd()->Camera()->draw_mode = cd_texture;
309     Map_BuildBrushData();
310   }
311
312   Sys_UpdateWindows (W_ALL);
313 }
314
315 /*!
316 gamma correction stuff
317 took out of QERApp_LoadTextureRGBA for clarity
318 */
319 byte g_gammatable[256];
320 void ResampleGamma(float fGamma)
321 {
322   int i,inf;
323   if (fGamma == 1.0)
324   {
325     for (i = 0; i < 256; i++)
326       g_gammatable[i] = i;
327   } else
328   {
329     for (i = 0; i < 256; i++)
330     {
331       inf = (int)( 255.0f * pow( (i + 0.5f) / 255.5f , fGamma ) + 0.5f );
332       if (inf < 0)
333         inf = 0;
334       if (inf > 255)
335         inf = 255;
336       g_gammatable[i] = inf;
337     }
338   }
339 }
340
341 /*!
342 this function does the actual processing of raw RGBA data into a GL texture
343 it will also generate the mipmaps
344 it looks like pPixels nWidth nHeight are the only relevant parameters
345 */
346 qtexture_t *QERApp_LoadTextureRGBA(unsigned char* pPixels, int nWidth, int nHeight)
347 {
348   static float fGamma = -1;
349   float total[3];
350   byte  *outpixels = NULL;
351   int   i, j, resampled, width2, height2, width3, height3;
352   int   max_tex_size = 0, mip = 0;
353   int   nCount = nWidth * nHeight;
354
355   if (fGamma != g_qeglobals.d_savedinfo.fGamma)
356   {
357     fGamma = g_qeglobals.d_savedinfo.fGamma;
358     ResampleGamma(fGamma);
359   }
360
361   qglGetIntegerv(GL_MAX_TEXTURE_SIZE, &max_tex_size);
362   if (!max_tex_size)
363     max_tex_size = 1024;
364
365   qtexture_t *q = (qtexture_t*)g_malloc(sizeof(*q));
366   q->width = nWidth;
367   q->height = nHeight;
368
369   total[0] = total[1] = total[2] = 0.0f;
370
371   // resample texture gamma according to user settings
372   for (i = 0; i < (nCount * 4); i += 4)
373   {
374     for (j = 0; j < 3; j++)
375     {
376       total[j] += (pPixels + i)[j];
377       byte b = (pPixels + i)[j];
378       (pPixels + i)[j] = g_gammatable[b];
379     }
380   }
381
382   q->color[0] = total[0] / (nCount * 255);
383   q->color[1] = total[1] / (nCount * 255);
384   q->color[2] = total[2] / (nCount * 255);
385
386   qglGenTextures (1, &q->texture_number);
387
388   qglBindTexture( GL_TEXTURE_2D, q->texture_number );
389
390   SetTexParameters();
391
392   width2 = 1; while (width2 < nWidth) width2 <<= 1;
393   height2 = 1; while (height2 < nHeight) height2 <<= 1;
394
395   width3 = width2;
396   height3 = height2;
397   while (width3 > max_tex_size) width3 >>= 1;
398   while (height3 > max_tex_size) height3 >>= 1;
399   if (width3 < 1) width3 = 1;
400   if (height3 < 1) height3 = 1;
401
402   if (!(width2 == nWidth && height2 == nHeight)) {
403     resampled = 1;
404     outpixels = (byte *)malloc(width2 * height2 * 4);
405     R_ResampleTexture(pPixels, nWidth, nHeight, outpixels, width2, height2, 4);
406   } else {
407     resampled = 0;
408     outpixels = pPixels;
409   }
410
411   while (width2 > width3 || height2 > height3)
412   {
413     GL_MipReduce(outpixels, outpixels, width2, height2, width3, height3);
414
415     if (width2 > width3)
416       width2 >>= 1;
417     if (height2 > height3)
418       height2 >>= 1;
419   }
420
421   qglTexImage2D(GL_TEXTURE_2D, mip++, g_qeglobals.texture_components, width2, height2, 0, GL_RGBA, GL_UNSIGNED_BYTE, outpixels);
422   while (width2 > 1 || height2 > 1)
423   {
424     GL_MipReduce(outpixels, outpixels, width2, height2, 1, 1);
425
426     if (width2 > 1)
427       width2 >>= 1;
428     if (height2 > 1)
429       height2 >>= 1;
430
431     qglTexImage2D(GL_TEXTURE_2D, mip++, g_qeglobals.texture_components, width2, height2, 0, GL_RGBA, GL_UNSIGNED_BYTE, outpixels);
432   }
433
434   qglBindTexture(GL_TEXTURE_2D, 0);
435   if (resampled)
436     free(outpixels);
437
438   return q;
439 }
440
441 /*
442 ==================
443 DumpUnreferencedShaders
444 usefull function: dumps the list of .shader files that are not referenced to the console
445 ==================
446 */
447 void DumpUnreferencedShaders()
448 {
449   GSList *lst, *sh, *files;
450   bool bFound = false;
451
452   files = vfsGetFileList ("scripts", "shader");
453   for (lst = files; lst; lst = lst->next)
454   {
455     bool listed = false;
456
457     for (sh = l_shaderfiles; sh != NULL; sh = g_slist_next (sh))
458       if (!strcmp ((char*)sh->data, (char*)lst->data))
459       {
460         listed = true;
461         break;
462       }
463
464     if (!listed)
465     {
466       if (!bFound)
467       {
468         bFound = true;
469         Sys_FPrintf (SYS_WRN, "Following shader files are not referenced in shaderlist.txt:\n");
470       }
471       Sys_FPrintf (SYS_WRN, "%s\n", (char*)lst->data);
472     }
473   }
474
475   vfsClearFileDirList (&files);
476 }
477
478 /*
479 ==================
480 BuildShaderList
481 build a CStringList of shader names
482 ==================
483 */
484 void BuildShaderList()
485 {
486   int count;
487   char filename[1024];
488   char *pBuff;
489   char dirstring[NAME_MAX];
490   int nLen;
491   if (l_shaderfiles!=NULL)
492   {
493     g_slist_free(l_shaderfiles);
494     l_shaderfiles = NULL;
495   }
496
497   if (g_pGameDescription->mGameFile != "hl.game")
498   {
499     strcpy(filename, g_pGameDescription->mShaderlist.GetBuffer());
500     count = vfsGetFileCount(filename, 0 );
501     if (count==0)
502     {
503       Sys_FPrintf(SYS_ERR, "Couldn't find '%s'\n", g_pGameDescription->mShaderlist.GetBuffer());
504       return;
505     }
506     // NOTE TTimo we use vfsGetFullPath solely to get the full path of the shader list we are gonna load
507     //   but we actually send the relative path to vfsLoadFile
508     //   so let's hope there is no disparity between the two functions
509     if (!vfsGetFullPath(filename, 0, 0))
510     {
511       Sys_FPrintf(SYS_ERR, "Couldn't find full path for '%s'\n", g_pGameDescription->mShaderlist.GetBuffer());
512       Sys_FPrintf(SYS_ERR, "did you hit bug http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=130 ?\n");
513       return;
514     }
515     Sys_Printf("Parsing shader files from %s\n", vfsGetFullPath(filename, 0, 0));
516     nLen = vfsLoadFile (filename, reinterpret_cast<void**>(&pBuff), 0);
517     if (nLen > 0)
518     {
519       StartTokenParsing(pBuff);
520       nLen = 0;
521       while (GetToken(true))
522       {
523         GSList *tmp;
524         bool found = false;
525
526         // each token should be a shader filename
527         sprintf(dirstring, "%s.shader", token);
528
529         for (tmp = l_shaderfiles; tmp != NULL; tmp = tmp->next)
530         {
531           if (!strcmp (dirstring, (char*)tmp->data))
532           {
533             found = true;
534             Sys_FPrintf(SYS_WRN, "duplicate entry \"%s\" in shaderlist.txt\n", (char*)tmp->data);
535             break;
536           }
537         }
538
539         if (!found)
540         {
541           l_shaderfiles = g_slist_append (l_shaderfiles, strdup (dirstring));
542           nLen++;
543         }
544       }
545       g_free(pBuff);
546     }
547   }
548 }
549
550 /*
551 ==================
552 FillTextureMenu
553
554 ==================
555 */
556 void ClearGSList (GSList* lst)
557 {
558   GSList *p = lst;
559   while (p)
560   {
561     free (p->data);
562     p = g_slist_remove (p, p->data);
563   }
564 }
565
566 void FillTextureMenu (GSList** pArray)
567 {
568   GtkWidget *menu, *sep, *item; // point to the Textures GtkMenu and to the last separator
569   GList *lst;
570   GSList *texdirs = NULL;
571   GSList *texdirs_tmp = NULL;
572   GSList *p;
573   char dirRoot[NAME_MAX];
574
575   // delete everything
576   menu = GTK_WIDGET (g_object_get_data (G_OBJECT (g_qeglobals_gui.d_main_window), "menu_textures"));
577   sep = GTK_WIDGET (g_object_get_data (G_OBJECT (g_qeglobals_gui.d_main_window), "menu_textures_separator"));
578   lst = g_list_find (gtk_container_children (GTK_CONTAINER (menu)), sep);
579   while (lst->next)
580   {
581     // these delete functions are recursive, it's gonna free all submenus
582     gtk_widget_destroy (GTK_WIDGET (lst->next->data));
583     // lst is no longer relevant, need to get it again
584     lst = g_list_find (gtk_container_children (GTK_CONTAINER (menu)), sep);
585   }
586
587   texture_nummenus = 0;
588
589   // add everything
590   if (!g_qeglobals.d_project_entity)
591     return;
592
593   // scan texture dirs and pak files only if not restricting to shaderlist
594   if (!g_PrefsDlg.m_bTexturesShaderlistOnly)
595   {
596     texdirs_tmp = vfsGetDirList ("textures/");
597     for (p=texdirs_tmp; p; p=g_slist_next(p))
598     {
599       // Hydra: erm, this didn't used to do anything except leak memory...
600       // For Halflife support this is required to work however.
601       // g_slist_append(texdirs, p->data);
602       texdirs = g_slist_append(texdirs, strdup((char *)p->data));
603     }
604     vfsClearFileDirList (&texdirs_tmp);
605   }
606
607   // scan the shaders in shaderlist.txt
608   BuildShaderList ();
609   PreloadShaders ();
610   DumpUnreferencedShaders ();
611   while (l_shaderfiles != NULL)
612   {
613     char shaderfile[PATH_MAX];
614     gboolean found = FALSE;
615
616     ExtractFileName ((char*)l_shaderfiles->data, shaderfile);
617     StripExtension (shaderfile);
618     g_strdown (shaderfile);
619
620     for (GSList *tmp = texdirs; tmp; tmp = g_slist_next (tmp))
621       if (!strcasecmp ((char*)tmp->data, shaderfile))
622       {
623               found = TRUE;
624               break;
625       }
626
627     if (!found)
628       texdirs = g_slist_prepend (texdirs, strdup (shaderfile));
629
630     free (l_shaderfiles->data);
631     l_shaderfiles = g_slist_remove (l_shaderfiles, l_shaderfiles->data);
632   }
633
634   // sort the list
635   texdirs = g_slist_sort (texdirs, (GCompareFunc)strcmp);
636
637   GSList *temp = texdirs;
638   while (temp)
639   {
640     char* ptr = strchr ((char*)temp->data, '_');
641
642     // do we shrink the menus?
643     if (ptr != NULL)
644     {
645       // extract the root
646       strcpy (dirRoot, (char*)temp->data);
647       dirRoot[ptr - (char*)temp->data + 1] = 0;
648
649       // we shrink only if we have at least two things to shrink :-)
650       if (temp->next && (strstr ((char*)temp->next->data, dirRoot) == (char*)temp->next->data))
651       {
652               GtkWidget *pSubMenu = gtk_menu_new ();
653         GtkWidget *pSubMenuRef = pSubMenu;
654               // keep going...
655               do
656               {
657                 item = gtk_menu_item_new_with_label ((char*)temp->data);
658                 gtk_widget_show (item);
659           CheckMenuSplitting (pSubMenu);
660                 gtk_container_add (GTK_CONTAINER (pSubMenu), item);
661                 gtk_signal_connect (GTK_OBJECT (item), "activate", GTK_SIGNAL_FUNC (HandleCommand),
662                                     GINT_TO_POINTER (CMD_TEXTUREWAD+texture_nummenus));
663
664                 strcpy (texture_menunames[texture_nummenus], (char*)temp->data);
665                 strcat (texture_menunames[texture_nummenus], "/");
666                 if (pArray)
667                   *pArray = g_slist_append (*pArray, strdup ((char*)temp->data));
668                 if (++texture_nummenus == MAX_TEXTUREDIRS)
669                 {
670                   Sys_Printf("WARNING: max texture directories count has been reached!\n");
671                   // push submenu and get out
672                   item = gtk_menu_item_new_with_label (dirRoot);
673                   gtk_widget_show (item);
674                   gtk_container_add (GTK_CONTAINER (menu), item);
675                   gtk_menu_item_set_submenu (GTK_MENU_ITEM (item), pSubMenu);
676                   ClearGSList (texdirs);
677                   return;
678                 }
679                 temp = temp->next;
680               }
681         while (temp && (strstr((char*)temp->data, dirRoot)==temp->data));
682
683         ptr = strchr (dirRoot, '_');
684         *ptr = 0;
685               item = gtk_menu_item_new_with_label (dirRoot);
686               gtk_widget_show (item);
687               CheckMenuSplitting (menu);
688               gtk_container_add (GTK_CONTAINER (menu), item);
689         gtk_menu_item_set_submenu (GTK_MENU_ITEM (item), pSubMenuRef);
690               continue;
691       }
692     }
693
694     item = gtk_menu_item_new_with_label ((char*)temp->data);
695     gtk_widget_show (item);
696     CheckMenuSplitting (menu);
697     gtk_container_add (GTK_CONTAINER (menu), item);
698     gtk_signal_connect (GTK_OBJECT (item), "activate", GTK_SIGNAL_FUNC (HandleCommand),
699                         GINT_TO_POINTER (CMD_TEXTUREWAD+texture_nummenus));
700
701     strcpy (texture_menunames[texture_nummenus], (char*)temp->data);
702     strcat (texture_menunames[texture_nummenus], "/");
703     if (pArray)
704       *pArray = g_slist_append (*pArray, strdup ((char*)temp->data));
705     if (++texture_nummenus == MAX_TEXTUREDIRS)
706     {
707       Sys_Printf("WARNING: max texture directories count has been reached!\n");
708       ClearGSList (texdirs);
709       return;
710     }
711
712     temp = temp->next;
713   }
714   ClearGSList (texdirs);
715 }
716
717 /*
718 ==============
719 Texture_ShowDirectory
720 relies on texture_directory global for the directory to use
721 called by
722   void Texture_ShowDirectory (int menunum, bool bLinked)
723   void  Texture_ShowDirectory (char* pPath, bool bLinked)
724 1) Load the shaders for the given directory
725 2) Scan the remaining texture, load them and assign them a default shader (the "noshader" shader)
726 NOTE: when writing a texture plugin, or some texture extensions, this function may need to be overriden, and made
727   available through the IShaders interface
728 NOTE: for texture window layout:
729   all shaders are stored with alphabetical order after load
730   previously loaded and displayed stuff is hidden, only in-use and newly loaded is shown
731   ( the GL textures are not flushed though)
732 ==============
733 */
734 void Texture_ShowDirectory ()
735 {
736   char  name[1024];
737   char  dirstring[1024];
738   CString strTemp;
739   int shaders_count = 0;
740   int textures_count = 0;
741   GSList *files = NULL, *temp;
742
743   g_bScreenUpdates = false;
744
745   // refresh the in-use textures: that will clear the IsDisplayed flag on unused stuff
746   // and leave it on in-use so they'll still be displayed
747   Texture_ShowInuse();
748   // and textures loaded in the following lines will be displayed as well...
749   // NOTE: shaders that are not in use but have been loaded previously are still in memory. But they don't get displayed.
750
751   g_qeglobals.d_texturewin.originy = 0;
752   // load texture_directory.shader
753   // NOTE: because of above call to Texture_ClearInuse, g_ActiveShaders will have the newly loaded shaders only
754   // we'll use that later to check if textures have a shader associated or not
755   // NOTE: all shaders loaded through QERApp_LoadShadersFromDir will get their InUse flag to True, we'll need a call to Texture_ShowInUse for later cleanup/adjustment
756   // NOTE: QERApp_LoadShadersFromDir has two criterions for loading a shader:
757   //   the shaderfile is texture_directory (like "museum" will load everything in museum.shader)
758   //   the shader name contains texture_directory (like "base_floor" will load museum.shader::base_floor/concfloor_rain)
759   shaders_count = QERApp_LoadShadersFromDir(texture_directory);
760   // load remaining texture files
761   // if a texture is already in use to represent a shader, ignore it
762
763   // need this function "GSList *lst SynapseServer::GetMinorList(char *major_name);"
764
765   sprintf (dirstring, "textures/%s", texture_directory);
766   g_ImageManager.BeginExtensionsScan();
767   const char* ext;
768   while((ext=g_ImageManager.GetNextExtension()) != NULL)
769   {
770     files = g_slist_concat(files, vfsGetFileList (dirstring, ext));
771   }
772
773   for (temp = files; temp; temp = temp->next)
774   {
775     sprintf(name, "%s%s", texture_directory, (char*)temp->data);
776
777       StripExtension (name);
778       strTemp = name;
779       strTemp.MakeLower();
780
781     if (strTemp.Find(".specular") >= 0 ||
782          strTemp.Find(".glow") >= 0 ||
783          strTemp.Find(".bump") >= 0 ||
784          strTemp.Find(".diffuse") >= 0 ||
785          strTemp.Find(".blend") >= 0 ||
786                strTemp.Find(".alpha") >= 0)
787          continue;
788
789     // avoid ever loading a texture name with spaces
790     if (strTemp.Find(" ") >= 0)
791     {
792       Sys_FPrintf(SYS_WRN, "WARNING: Skipping texture name with spaces [%s]\n", strTemp.GetBuffer());
793       continue;
794     }
795
796     // build a texture name that fits the conventions for qtexture_t::name
797     char stdName[1024];
798     sprintf( stdName, "textures/%s", name );
799     // check if this texture doesn't have a shader
800     if (!QERApp_ActiveShader_ForTextureName( stdName ))
801     {
802       QERApp_CreateShader_ForTextureName (stdName);
803       textures_count++;
804     }
805   }
806
807   Sys_Printf("Loaded %d shaders and created default shader for %d orphan textures.\n",
808              shaders_count, textures_count );
809
810   vfsClearFileDirList (&files);
811
812   // sort for displaying
813   QERApp_SortActiveShaders();
814
815   sprintf (name, "Textures: %s", texture_directory);
816   gtk_window_set_title (GTK_WINDOW (g_qeglobals_gui.d_entity), name);
817
818   // select the first texture in the list
819   if (!g_qeglobals.d_texturewin.texdef.GetName()[0])
820     SelectTexture (16, g_qeglobals.d_texturewin.height -16, false);
821
822   g_bScreenUpdates = true;
823
824   Sys_UpdateWindows (W_TEXTURE);
825 }
826
827 /*
828 ==============
829 Texture_ShowDirectory
830 1) Load the shaders for the given directory
831 2) Scan the remaining texture, load them and assign them a default shader (the "noshader" shader)
832 NOTE: when writing a texture plugin, or some texture extensions, this function may need to be overriden, and made
833   available through the IShaders interface
834 ==============
835 */
836 void Texture_ShowDirectory (int menunum)
837 {
838   strcpy (texture_directory, texture_menunames[menunum-CMD_TEXTUREWAD]);
839   Texture_ShowDirectory();
840 }
841
842 // scroll origin so the current texture is completely on screen
843 // if current texture is not displayed, nothing is changed
844 void Texture_ResetPosition()
845 {
846   qtexture_t  *q;
847   int  x,y;
848
849   //this shouldn't ever happen, we startup with notex
850   if (!g_qeglobals.d_texturewin.texdef.GetName()[0]) {
851     return;
852   }
853
854   // otherwise position with current texture shown
855   // this used to be in Texture_SetTexture
856   Texture_StartPos ();
857   while (1)
858   {
859     // NOTE: return value is == pCurrentShader and pCurrentShader->getTexture == current_texture
860     Texture_NextPos (&x, &y);
861     q = current_texture;
862     // if the current texture never found (because // 'show shaders' is off,
863     // for example), do nothing
864     if (!q)
865       break;
866
867     int nHeight = (int)(q->height * ((float)g_PrefsDlg.m_nTextureScale / 100));
868     // we have found when texdef->name and the shader name match
869     // NOTE: as everywhere else for our comparisons, we are not case sensitive
870     if (!strcmpi( g_qeglobals.d_texturewin.texdef.GetName(), pCurrentShader->getName() ))
871     {
872       // take care of calls before initialized
873       if ( !g_qeglobals.d_texturewin.height) {
874         g_qeglobals.d_texturewin.originy = 0;
875         break;
876       }
877       // if the bottom of our selected texture will fit with origin 0, use that
878       // to prevent scrolling uglyness (stuff scrolled off screen when
879       // everything would fit)
880       if ( -(y -nHeight-2*FONT_HEIGHT) <  g_qeglobals.d_texturewin.height) {
881         g_qeglobals.d_texturewin.originy = 0;
882         break;
883       }
884       // if current is off the top of the window, move it to the top
885       if (y > g_qeglobals.d_texturewin.originy)
886       {
887         g_qeglobals.d_texturewin.originy = y;
888         break;
889       }
890
891       // if current is off the bottom, put it on the bottom
892       if (y-nHeight-2*FONT_HEIGHT < g_qeglobals.d_texturewin.originy-g_qeglobals.d_texturewin.height)
893       {
894         g_qeglobals.d_texturewin.originy = y-nHeight-2*FONT_HEIGHT+g_qeglobals.d_texturewin.height;
895         break;
896       }
897       // if we made it here, it should already be in view
898       break;
899     }
900   }
901   Sys_UpdateWindows (W_TEXTURE);
902 }
903
904 /*
905 ==============
906 Texture_ShowAll
907 will set the IsDisplayed flag on all the active shaders, so we see everything that's currently in memory
908 ==============
909 */
910 void Texture_ShowAll()
911 {
912   char name[1024];
913
914 #ifdef _DEBUG
915   if (g_bShowAllShaders)
916     Sys_Printf("WARNING: already showing all shaders\n");
917 #endif
918   QERApp_ActiveShaders_SetDisplayed(true);
919   g_bShowAllShaders = true;
920   // put some information in the texture window title?
921   sprintf (name, "Textures: in use");
922   gtk_window_set_title (GTK_WINDOW (g_qeglobals_gui.d_entity), name);
923   Sys_UpdateWindows (W_TEXTURE);
924 }
925
926 /*
927 ==============
928 Texture_ShowInuse
929 clear all IsDisplayed flags
930 scan the map, set IsInUse (will set IsDisplayed on the way)
931 NOTE: don't sort the textures, don't update the windows (it's used in several contexts, not always necessary to do either)
932 ==============
933 */
934 void WINAPI Texture_ShowInuse (void)
935 {
936   face_t  *f;
937   brush_t *b;
938   char  name[1024];
939
940   g_qeglobals.d_texturewin.originy = 0;
941
942   // purge
943   QERApp_ActiveShaders_SetDisplayed(false);
944   // scan and only display in-use stuff
945   Sys_Status("Selecting active textures", 0);
946
947   for (b=active_brushes.next ; b != NULL && b != &active_brushes ; b=b->next)
948   {
949     if (b->patchBrush)
950     {
951       b->pPatch->pShader->SetInUse(true);
952     } else
953     {
954       for (f=b->brush_faces ; f ; f=f->next)
955       {
956         f->pShader->SetInUse(true);
957       }
958     }
959   }
960   for (b=selected_brushes.next ; b != NULL && b != &selected_brushes ; b=b->next)
961   {
962     if (b->patchBrush)
963     {
964       b->pPatch->pShader->SetInUse(true);
965     } else
966     {
967       for (f=b->brush_faces ; f ; f=f->next)
968       {
969         f->pShader->SetInUse(true);
970       }
971     }
972   }
973
974   // we are no longer showing everything
975   g_bShowAllShaders = false;
976   // put some information in the texture window title?
977   sprintf (name, "Textures: in use");
978   gtk_window_set_title (GTK_WINDOW (g_qeglobals_gui.d_entity), name);
979
980
981   // select the first texture in the list
982   if (!g_qeglobals.d_texturewin.texdef.GetName()[0])
983   {
984     SelectTexture (16, g_qeglobals.d_texturewin.height -16, false);
985   }
986 }
987
988 void Texture_ShowStartupShaders()
989 {
990   if (g_PrefsDlg.m_nShader == PrefsDlg::SHADER_COMMON)
991   {
992     // RIANT
993     // HACK FOR JK2 SUPPORT
994     if (g_pGameDescription->mGameFile == "jk2.game" || g_pGameDescription->mGameFile == "ja.game")
995     {
996       strcpy (texture_directory, "system/");
997     }
998     // RIANT
999     // HACK FOR SOF2 SUPPORT
1000     else if (g_pGameDescription->mGameFile == "sof2.game")
1001     {
1002       strcpy (texture_directory, "tools/");
1003     }
1004     else strcpy (texture_directory, "common/");
1005     Texture_ShowDirectory ();
1006   }
1007
1008   if (g_PrefsDlg.m_nShader == PrefsDlg::SHADER_ALL) {
1009     int    count;
1010     char   filename[1024];
1011     char   *pBuff;
1012     char   dirstring[NAME_MAX];
1013     int    nLen;
1014     GSList *shaderfiles = NULL;
1015
1016     strcpy(filename, g_pGameDescription->mShaderlist.GetBuffer());
1017     count = vfsGetFileCount(filename, 0);
1018     if (count == 0)
1019     {
1020       Sys_FPrintf(SYS_ERR, "Couldn't find '%s'\n", g_pGameDescription->mShaderlist.GetBuffer());
1021       return;
1022     }
1023
1024     if (!vfsGetFullPath(filename, 0, 0))
1025     {
1026       Sys_FPrintf(SYS_ERR, "Couldn't find full path for '%s'\n", g_pGameDescription->mShaderlist.GetBuffer());
1027       Sys_FPrintf(SYS_ERR, "did you hit bug http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=130 ?\n");
1028       return;
1029     }
1030
1031     Sys_Printf("Parsing shader files from %s\n", vfsGetFullPath(filename, 0, 0));
1032     nLen = vfsLoadFile (filename, reinterpret_cast<void**>(&pBuff), 0);
1033     if (nLen > 0)
1034     {
1035       StartTokenParsing(pBuff);
1036       nLen = 0;
1037       while (GetToken(true))
1038       {
1039         GSList *tmp;
1040         bool found = false;
1041
1042         // each token should be a shader filename
1043         sprintf(dirstring, "%s.shader", token);
1044
1045         for (tmp = shaderfiles; tmp != NULL; tmp = tmp->next)
1046         {
1047           if (!strcmp (dirstring, (char*)tmp->data))
1048           {
1049             found = true;
1050             Sys_FPrintf(SYS_WRN, "duplicate entry \"%s\" in shaderlist.txt\n", (char*)tmp->data);
1051             break;
1052           }
1053         }
1054
1055         if (!found)
1056         {
1057           shaderfiles = g_slist_append (l_shaderfiles, strdup (dirstring));
1058           strcpy (texture_directory, dirstring);
1059           Texture_ShowDirectory ();
1060           nLen++;
1061         }
1062       }
1063       g_free(pBuff);
1064     }
1065   }
1066 }
1067
1068 /*
1069 ============================================================================
1070
1071 TEXTURE LAYOUT
1072
1073 TTimo: now based on a rundown through all the shaders
1074 nActiveShadersCount: number of shader that have a qtexture_t and may be displayed in the tex window
1075 nCurrentShader: index of active shader that has the current_texture
1076 pCurrentShader: IShader* for current shader
1077 NOTE: we expect the Active shaders count doesn't change during a Texture_StartPos .. Texture_NextPos cycle
1078   otherwise we may need to rely on a list instead of an array storage
1079 ============================================================================
1080 */
1081
1082 void Texture_StartPos (void)
1083 {
1084   //++timo TODO: check use of current_texture and current_row?
1085   current_x = 8;
1086   current_y = -8;
1087   current_row = 0;
1088   nActiveShadersCount = QERApp_GetActiveShaderCount();
1089   nCurrentShader = -1;
1090   current_texture = NULL;
1091   pCurrentShader = NULL;
1092 }
1093
1094 // if texture_showinuse jump over non in-use textures
1095 // it's not very clear what should be done here and what in Texture_Draw .. maybe merging the two would do good
1096 IShader* Texture_NextPos (int *x, int *y)
1097 {
1098   qtexture_t* q;
1099   while (1)
1100   {
1101     if (nCurrentShader >= nActiveShadersCount - 1)
1102     {
1103       // no more shaders
1104       current_texture = NULL;
1105       pCurrentShader = NULL;
1106       return NULL;
1107     }
1108     nCurrentShader++;
1109     pCurrentShader = QERApp_ActiveShader_ForIndex(nCurrentShader);
1110     if (pCurrentShader == NULL)
1111     {
1112       Sys_Printf("ERROR: unexpected pCurrentShader == NULL in Texture_NextPos\n");
1113       return NULL;
1114     }
1115     current_texture = pCurrentShader->getTexture();
1116     q = current_texture;
1117
1118     if (!q)
1119     {
1120       Sys_Printf("WARNING: found an IShader without qtexture_t in Texture_NextPos\n");
1121       return NULL;
1122     }
1123
1124     /*
1125     Never show anything other than "textures/" path,
1126     This is for q1/q2/q3 .map format, which expects "textures/" path on everything we apply
1127     */
1128     if(strncmp(pCurrentShader->getName(), "textures/", 9) != 0)
1129       continue;
1130
1131     // don't show shaders?
1132     if (!(g_PrefsDlg.m_bShowShaders || pCurrentShader->IsDefault()))
1133       continue;
1134
1135     if (g_PrefsDlg.m_bTextureWindow)
1136     {
1137       // some basic filtering
1138       if (!g_pParentWnd->GetTexWnd()->CheckFilter( pCurrentShader->getName() ))
1139         continue;
1140     }
1141
1142     //++timo FIXME: texture_showinuse is useless? with the menu and reload we just refresh the IsDisplayed flag
1143     // but the IsInUse is only relevant to draw the green outline
1144     if (pCurrentShader->IsDisplayed())
1145       break;
1146
1147     continue;
1148   }
1149
1150   int nWidth = (int)(q->width * ((float)g_PrefsDlg.m_nTextureScale / 100));
1151   int nHeight = (int)(q->height * ((float)g_PrefsDlg.m_nTextureScale / 100));
1152   if (current_x + nWidth > g_qeglobals.d_texturewin.width-8 && current_row)
1153   { // go to the next row unless the texture is the first on the row
1154     current_x = 8;
1155     current_y -= current_row + FONT_HEIGHT + 4;
1156     current_row = 0;
1157   }
1158
1159   *x = current_x;
1160   *y = current_y;
1161
1162   // Is our texture larger than the row? If so, grow the
1163   // row height to match it
1164
1165   if (current_row < nHeight)
1166     current_row = nHeight;
1167
1168   // never go less than 64, or the names get all crunched up
1169   current_x += nWidth < 64 ? 64 : nWidth;
1170   current_x += 8;
1171
1172   return pCurrentShader;
1173 }
1174
1175 /*
1176 ============================================================================
1177
1178   MOUSE ACTIONS
1179
1180 ============================================================================
1181 */
1182
1183 static  int textures_cursorx, textures_cursory;
1184
1185 /*
1186 ============
1187 Texture_SetTexture
1188
1189 brushprimit_texdef must be understood as a qtexture_t with width=2 height=2 ( the default one )
1190 ============
1191 */
1192
1193 //++timo NOTE: this is a mix of Shader module stuff and texture explorer
1194 // it might need to be split in parts or moved out .. dunno
1195 void WINAPI Texture_SetTexture (texdef_t *texdef, brushprimit_texdef_t *brushprimit_texdef, bool bFitScale, IPluginTexdef *pTexdef, bool bSetSelection )
1196 {
1197   if (texdef->GetName()[0] == '(')
1198   {
1199     Sys_Status("Can't select an entity texture", 0);
1200     return;
1201   }
1202   g_qeglobals.d_texturewin.texdef = *texdef;
1203   g_qeglobals.d_texturewin.texdef.flags &= ~SURF_KEEP;
1204   g_qeglobals.d_texturewin.texdef.contents &= ~CONTENTS_KEEP;
1205   // store the shader pointer
1206   // NOTE: maybe passing the shader pointer would help?
1207   g_qeglobals.d_texturewin.pShader->DecRef();
1208   g_qeglobals.d_texturewin.pShader = QERApp_Shader_ForName(texdef->GetName());
1209   g_qeglobals.d_texturewin.pShader->IncRef();
1210   // set this shader as in use
1211   g_qeglobals.d_texturewin.pShader->SetInUse( true );
1212   // store the texture coordinates for new brush primitive mode
1213   // be sure that all the callers are using the default 2x2 texture
1214   if (g_qeglobals.m_bBrushPrimitMode)
1215   {
1216     g_qeglobals.d_texturewin.brushprimit_texdef = *brushprimit_texdef;
1217   }
1218
1219   g_dlgFind.updateTextures(texdef->GetName());
1220   if (!g_dlgFind.isOpen() && bSetSelection)
1221   {
1222     Select_SetTexture(texdef,brushprimit_texdef,bFitScale);
1223   }
1224
1225   //plugins: send a message telling that the selected texture may have changed
1226   DispatchRadiantMsg( RADIANT_TEXTURE );
1227
1228   // scroll origin so the texture is completely on screen
1229   // takes texdef from g_qeglobals.d_texturewin.texdef, set above
1230   Texture_ResetPosition();
1231 }
1232
1233 void ViewShader(const char *pFile, const char *pName)
1234 {
1235   //  ask the vfs to build the full path to the file
1236   // (i.e. the first one found)
1237   char *fullName = vfsGetFullPath(pFile,0,0);
1238   if (fullName == NULL)
1239   {
1240     Sys_FPrintf (SYS_ERR, "Couldn't get a full path to the shader file: %s\n", pFile);
1241     return;
1242   }
1243
1244   char* pBuff = NULL;
1245   int nSize = vfsLoadFullPathFile(fullName, reinterpret_cast<void**>(&pBuff));
1246   if (nSize <= 0)
1247   {
1248     Sys_FPrintf (SYS_ERR, "Failed to load shader file %s\n", fullName);
1249     return;
1250   }
1251   // look for the shader declaration
1252   int nStart;
1253   CString strFind = pName;
1254   CString strLook = pBuff;
1255   strLook.MakeLower();
1256   strFind.MakeLower();
1257   // offset used when jumping over commented out definitions
1258   int nOffset = 0;
1259   while (true)
1260   {
1261     nStart = strLook.Find(strFind, nOffset);
1262     if (nStart == -1)
1263       break;
1264     // we have found something, maybe it's a commented out shader name?
1265     char *strCheck = new char[strLook.GetLength()+1];
1266     strcpy( strCheck, strLook.GetBuffer() );
1267     strCheck[nStart] = 0;
1268     char *pCheck = strrchr( strCheck, '\n' );
1269     // if there's a commentary sign in-between we'll continue
1270     if (pCheck && strstr( pCheck, "//" ))
1271     {
1272       delete[] strCheck;
1273       nOffset = nStart + 1;
1274       continue;
1275     }
1276     delete[] strCheck;
1277     nOffset = nStart;
1278     break;
1279   }
1280   // now close the file
1281   g_free(pBuff);
1282
1283   DoTextEditor (fullName, nOffset);
1284 }
1285
1286 /*
1287 ==============
1288 SelectTexture
1289
1290   By mouse click
1291 ==============
1292 */
1293 void SelectTexture (int mx, int my, bool bShift, bool bFitScale)
1294 {
1295   int   x, y;
1296   qtexture_t  *q;
1297   texdef_t  tex;
1298   brushprimit_texdef_t brushprimit_tex;
1299
1300   my += g_qeglobals.d_texturewin.originy-g_qeglobals.d_texturewin.height;
1301
1302   Texture_StartPos ();
1303   while (1)
1304   {
1305     // NOTE: return value is == pCurrentShader and pCurrentShader->getTexture == current_texture
1306     Texture_NextPos (&x, &y);
1307     q = current_texture;
1308     if (!q)
1309       break;
1310     int nWidth = (int)(q->width * ((float)g_PrefsDlg.m_nTextureScale / 100));
1311     int nHeight = (int)(q->height * ((float)g_PrefsDlg.m_nTextureScale / 100));
1312     if (mx > x && mx - x < nWidth
1313       && my < y && y - my < nHeight + FONT_HEIGHT)
1314     {
1315       if (bShift)
1316       {
1317         if (pCurrentShader->IsDefault())
1318           Sys_Printf("ERROR: %s is not a shader, it's a texture.\n", pCurrentShader->getName() );
1319         else
1320           ViewShader( pCurrentShader->getShaderFileName(), pCurrentShader->getName() );
1321       }
1322       else
1323       {
1324         memset (&tex, 0, sizeof(tex));
1325         memset (&brushprimit_tex, 0, sizeof(brushprimit_tex));
1326         if (g_qeglobals.m_bBrushPrimitMode)
1327         {
1328           // brushprimit fitted to a 2x2 texture
1329           brushprimit_tex.coords[0][0] = 1.0f;
1330           brushprimit_tex.coords[1][1] = 1.0f;
1331         }
1332         else
1333         {
1334           tex.scale[0] = g_pGameDescription->mTextureDefaultScale;
1335           tex.scale[1] = g_pGameDescription->mTextureDefaultScale;
1336         }
1337         tex.flags = pCurrentShader->getFlags();
1338         // TTimo - shader code cleanup
1339         // texdef.name is the name of the shader, not the name of the actual texture file
1340         tex.SetName(pCurrentShader->getName());
1341         // NOTE WARNING: Texture_SetTexture uses Texture_NextPos stuff to move the window position on to the texture
1342         // if there's some kind of fuckup in Texture_SetTexture you may end up with different pCurrentShader or even pCurrentShader == NULL
1343         // so we just consider pCurrentShader and current_texture are not valid after this point
1344         IShader *pAuxShader = pCurrentShader;
1345         Texture_SetTexture ( &tex, &brushprimit_tex, bFitScale, NULL); // Nurail
1346         CString strTex;
1347         CString strName;
1348         // if shader, print shader name, otherwise texture name
1349         //++timo FIXME: maybe CShader needs some properties between color / default / actual shader
1350 #ifdef _DEBUG
1351         // this one is never supposed to be set as current one
1352         if (pAuxShader->IsColor())
1353           Sys_Printf("ERROR: unexpected pCurrentShader->IsColor() in SelectTexture\n");
1354 #endif
1355         // NOTE: IsColor is false, IsDefault the only remaining property
1356         if (pAuxShader->IsDefault())
1357         {
1358           strName = q->name;
1359           // remove the "textures/" if needed
1360           if (strName.Find("textures/")!=-1)
1361             strName = strName.Mid(9);
1362         }
1363         else
1364         {
1365           strName = pAuxShader->getName();
1366         }
1367         strTex.Format("%s W: %i H: %i", strName.GetBuffer(), q->width, q->height);
1368         g_pParentWnd->SetStatusText(3, strTex);
1369       }
1370       return;
1371     }
1372   }
1373
1374   Sys_Status("Did not select a texture", 0);
1375 }
1376
1377 /*
1378 ==============
1379 Texture_MouseDown
1380 ==============
1381 */
1382 void Texture_MouseDown (int x, int y, int buttons)
1383 {
1384   Sys_GetCursorPos (&textures_cursorx, &textures_cursory);
1385
1386   // lbutton = select texture
1387   if (buttons == MK_LBUTTON || buttons == (MK_LBUTTON | MK_SHIFT) || buttons == (MK_LBUTTON | MK_CONTROL))
1388   {
1389     SelectTexture (x, g_qeglobals.d_texturewin.height - 1 - y, buttons & MK_SHIFT, buttons & MK_CONTROL);
1390     UpdateSurfaceDialog();
1391     UpdatePatchInspector();
1392   }
1393 }
1394
1395 /*
1396 ==============
1397 Texture_MouseMoved
1398 ==============
1399 */
1400
1401 void Texture_MouseMoved (int x, int y, int buttons)
1402 {
1403   int scale = 1;
1404
1405   if ( buttons & MK_SHIFT )
1406     scale = 4;
1407
1408   // rbutton = drag texture origin
1409   if (buttons & MK_RBUTTON)
1410   {
1411     Sys_GetCursorPos (&x, &y);
1412     if ( y != textures_cursory)
1413     {
1414       g_qeglobals.d_texturewin.originy += ( y-textures_cursory) * scale;
1415       if (g_qeglobals.d_texturewin.originy > 0)
1416         g_qeglobals.d_texturewin.originy = 0;
1417       Sys_SetCursorPos (textures_cursorx, textures_cursory);
1418
1419       // (g_PrefsDlg.m_bTextureScrollbar && g_qeglobals_gui.d_texture_scroll != NULL)
1420       // fixes broken texture scrolling when scrollbar is disabled
1421       GtkAdjustment *vadjustment = gtk_range_get_adjustment (GTK_RANGE (g_qeglobals_gui.d_texture_scroll));
1422       gtk_adjustment_set_value (vadjustment, abs(g_qeglobals.d_texturewin.originy));
1423       //
1424     }
1425     return;
1426   }
1427 }
1428
1429 /*
1430 ============================================================================
1431
1432 DRAWING
1433
1434 ============================================================================
1435 */
1436
1437 int imax(int iFloor, int i) { if (i>iFloor) return iFloor;return i;}
1438
1439 /*
1440 ============
1441 Texture_Draw
1442 TTimo: relying on the shaders list to display the textures
1443 we must query all qtexture_t* to manage and display through the IShaders interface
1444 this allows a plugin to completely override the texture system
1445 ============
1446 */
1447 void Texture_Draw (int width, int height)
1448 {
1449   int x, y, last_y = 0, last_height = 0, nWidth, nHeight;
1450   qtexture_t *q;
1451   char *name;
1452
1453   qglClearColor (g_qeglobals.d_savedinfo.colors[COLOR_TEXTUREBACK][0],
1454                  g_qeglobals.d_savedinfo.colors[COLOR_TEXTUREBACK][1],
1455                  g_qeglobals.d_savedinfo.colors[COLOR_TEXTUREBACK][2], 0);
1456   qglViewport (0,0,width,height);
1457   qglMatrixMode(GL_PROJECTION);
1458   qglLoadIdentity ();
1459
1460   qglClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1461   qglDisable (GL_DEPTH_TEST);
1462   qglDisable(GL_BLEND);
1463   qglOrtho (0, width, g_qeglobals.d_texturewin.originy-height, g_qeglobals.d_texturewin.originy, -100, 100);
1464   qglEnable (GL_TEXTURE_2D);
1465
1466   qglPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
1467   g_qeglobals.d_texturewin.width = width;
1468   g_qeglobals.d_texturewin.height = height;
1469
1470   Texture_StartPos();
1471   for (;;)
1472   {
1473     // NOTE: return value is == pCurrentShader and pCurrentShader->getTexture == current_texture
1474     Texture_NextPos (&x, &y);
1475     q = current_texture;
1476     if (!q)
1477       break;
1478
1479     nWidth = (int)(q->width * ((float)g_PrefsDlg.m_nTextureScale / 100));
1480     nHeight = (int)(q->height * ((float)g_PrefsDlg.m_nTextureScale / 100));
1481
1482     if (y != last_y)
1483     {
1484       last_y = y;
1485       last_height = 0;
1486     }
1487     last_height = MAX (nHeight, last_height);
1488
1489     // Is this texture visible?
1490     if ((y-nHeight-FONT_HEIGHT < g_qeglobals.d_texturewin.originy)
1491         && (y > g_qeglobals.d_texturewin.originy - height))
1492     {
1493       // borders rules:
1494       // if it's the current texture, draw a thick red line, else:
1495       // shaders have a white border, simple textures don't
1496       // if !texture_showinuse: (some textures displayed may not be in use)
1497       // draw an additional square around with 0.5 1 0.5 color
1498       if (!strcmpi(g_qeglobals.d_texturewin.texdef.GetName(), pCurrentShader->getName()))
1499       {
1500               qglLineWidth (3);
1501               qglColor3f (1,0,0);
1502               qglDisable (GL_TEXTURE_2D);
1503
1504               qglBegin (GL_LINE_LOOP);
1505               qglVertex2f (x-4,y-FONT_HEIGHT+4);
1506               qglVertex2f (x-4,y-FONT_HEIGHT-nHeight-4);
1507               qglVertex2f (x+4+nWidth,y-FONT_HEIGHT-nHeight-4);
1508               qglVertex2f (x+4+nWidth,y-FONT_HEIGHT+4);
1509               qglEnd ();
1510
1511               qglEnable (GL_TEXTURE_2D);
1512               qglLineWidth (1);
1513       }
1514       else
1515       {
1516               qglLineWidth (1);
1517               // shader border:
1518               if (!pCurrentShader->IsDefault())
1519               {
1520                 qglColor3f (1,1,1);
1521                 qglDisable (GL_TEXTURE_2D);
1522
1523                 qglBegin (GL_LINE_LOOP);
1524                 qglVertex2f (x-1,y+1-FONT_HEIGHT);
1525                 qglVertex2f (x-1,y-nHeight-1-FONT_HEIGHT);
1526                 qglVertex2f (x+1+nWidth,y-nHeight-1-FONT_HEIGHT);
1527                 qglVertex2f (x+1+nWidth,y+1-FONT_HEIGHT);
1528                 qglEnd ();
1529                 qglEnable (GL_TEXTURE_2D);
1530               }
1531
1532               // highlight in-use textures
1533               if (pCurrentShader->IsInUse())
1534               {
1535                 qglColor3f (0.5,1,0.5);
1536                 qglDisable (GL_TEXTURE_2D);
1537                 qglBegin (GL_LINE_LOOP);
1538                 qglVertex2f (x-3,y+3-FONT_HEIGHT);
1539                 qglVertex2f (x-3,y-nHeight-3-FONT_HEIGHT);
1540                 qglVertex2f (x+3+nWidth,y-nHeight-3-FONT_HEIGHT);
1541                 qglVertex2f (x+3+nWidth,y+3-FONT_HEIGHT);
1542                 qglEnd ();
1543                 qglEnable (GL_TEXTURE_2D);
1544               }
1545       }
1546
1547       // Draw the texture
1548       qglBindTexture (GL_TEXTURE_2D, q->texture_number);
1549       QE_CheckOpenGLForErrors();
1550       qglColor3f (1,1,1);
1551       qglBegin (GL_QUADS);
1552       qglTexCoord2f (0,0);
1553       qglVertex2f (x,y-FONT_HEIGHT);
1554       qglTexCoord2f (1,0);
1555       qglVertex2f (x+nWidth,y-FONT_HEIGHT);
1556       qglTexCoord2f (1,1);
1557       qglVertex2f (x+nWidth,y-FONT_HEIGHT-nHeight);
1558       qglTexCoord2f (0,1);
1559       qglVertex2f (x,y-FONT_HEIGHT-nHeight);
1560       qglEnd ();
1561
1562       // draw the texture name
1563       qglDisable (GL_TEXTURE_2D);
1564       qglColor3f (1,1,1);
1565
1566       qglRasterPos2f (x, y-FONT_HEIGHT+2);
1567
1568       // don't draw the directory name
1569       name = (char*)pCurrentShader->getName();
1570       name += strlen(name);
1571       while(name != (char*)pCurrentShader->getName() && *(name-1) != '/' && *(name-1) != '\\')
1572         name--;
1573
1574       gtk_glwidget_print_string(name);
1575       qglEnable (GL_TEXTURE_2D);
1576     }
1577   }
1578
1579   g_qeglobals.d_texturewin.m_nTotalHeight = abs(y) + last_height + FONT_HEIGHT + 4;
1580
1581   // reset the current texture
1582   qglBindTexture(GL_TEXTURE_2D, 0);
1583   qglFinish();
1584 }
1585
1586 //++timo seems we only know hard inits now..
1587 //void Texture_Init (bool bHardInit)
1588 void Texture_Init()
1589 {
1590   g_qeglobals.d_qtextures = NULL;
1591   // initialize the qtexture map
1592   if (g_qeglobals.d_qtexmap)
1593   {
1594     Sys_FPrintf(SYS_ERR, "TODO: delete g_qeglobals.d_qtexmap in Texture_Init\n");
1595   }
1596   g_qeglobals.d_qtexmap = g_hash_table_new (g_str_hash, g_str_equal);
1597   // initialize .. in some cases if no default texture / project loaded it crashes
1598   memset( &g_qeglobals.d_texturewin.texdef, 0, sizeof(g_qeglobals.d_texturewin.texdef) );
1599   g_qeglobals.d_texturewin.texdef.SetName(SHADER_NOT_FOUND);
1600   g_qeglobals.d_texturewin.pShader = QERApp_Shader_ForName(SHADER_NOT_FOUND);
1601 }
1602
1603 // FIXME TTimo this needs to move to the shader module along with l_shaderlist move
1604 // preload shader files that have been listed in shaderlist.txt
1605 void PreloadShaders()
1606 {
1607   GSList *lst = l_shaderfiles;
1608   Str shadername;
1609   while (lst)
1610   {
1611     shadername = g_pGameDescription->mShaderPath;
1612     shadername += (char*)lst->data;
1613     QERApp_LoadShaderFile(shadername.GetBuffer());
1614     lst = lst->next;
1615   }
1616 }
1617
1618 // TTimo: modified to expect the reletive path to the skin as input
1619 // will look into pak files if necessary
1620 // uses the shader code to load the texture Try_Texture_ForName
1621 // modified SkinInfo accordingly to store the qtexture_t and shader name (reletive version)
1622 // the .md3 have bundled filetype extension, but they don't fit with the actual data
1623 //   ex: models/mapobjects/gargoyle.tga doesn't exist, but models/mapobjects/gargoyle.jpg can be used instead
1624 //   so we remove the extension before load attempt
1625 int WINAPI Texture_LoadSkin(char *pName, int *pnWidth, int *pnHeight)
1626 {
1627   //  byte *pic = NULL;
1628   //  byte *pic32 = NULL;
1629   int nTex = -1;
1630   qtexture_t *qtex;
1631   SkinInfo *pInfo;
1632   const char *pCleanName;
1633
1634   int nSize = g_lstSkinCache.GetSize();
1635   pCleanName = QERApp_CleanTextureName( pName, false );
1636   for (int i = 0; i < nSize; i++)
1637   {
1638     SkinInfo *pInfo = reinterpret_cast<SkinInfo*>(g_lstSkinCache.GetAt(i));
1639     if (pInfo)
1640     {
1641       if (stricmp(pCleanName, pInfo->m_strName) == 0)
1642       {
1643         return pInfo->m_nTextureBind;
1644       }
1645     }
1646   }
1647
1648   // if the load is successfull, we get back a qtexture_t
1649   // we don't need to free it, it's in g_qeglobals.d_qtextures
1650   // NOTE: we need to free the SkinInfo though..
1651   qtex = QERApp_Try_Texture_ForName( pCleanName );
1652   if (qtex)
1653   {
1654     nTex = qtex->texture_number;
1655     pInfo = new SkinInfo(qtex->name, nTex, qtex);
1656   } else
1657   {
1658     pInfo = new SkinInfo(pCleanName, -1, NULL);
1659   }
1660   g_lstSkinCache.Add(pInfo);
1661
1662   return nTex;
1663 }
1664
1665 bool TexWnd::CheckFilter( const char* name )
1666 {
1667   const char* buf = gtk_entry_get_text (GTK_ENTRY (m_pFilter));
1668   if (strstr( name, buf ) != 0)
1669     return true;
1670   return false;
1671 }
1672
1673 // =============================================================================
1674 // static functions
1675
1676 static void vertical_scroll (GtkWidget *widget, gpointer data)
1677 {
1678   ((TexWnd*)data)->OnVScroll ();
1679 }
1680
1681 static void filter_changed (GtkWidget *widget, gpointer data)
1682 {
1683   CString str;
1684   str = gtk_entry_get_text (GTK_ENTRY (widget));
1685   ((TexWnd*)data)->UpdateFilter (str);
1686 }
1687
1688 // =============================================================================
1689 // TexWnd class
1690
1691 TexWnd::TexWnd()
1692 : GLWindow (FALSE)
1693 {
1694   m_pFilter = NULL;
1695   m_bNeedRange = true;
1696 }
1697
1698 TexWnd::~TexWnd()
1699 {
1700 }
1701
1702 void TexWnd::OnCreate ()
1703 {
1704   if (!MakeCurrent ())
1705     Error ("glMakeCurrent in TexWnd::OnCreate failed");
1706
1707   g_qeglobals_gui.d_texture = m_pWidget;
1708   g_nTextureOffset = 0;
1709
1710   GtkAdjustment *vadjustment = gtk_range_get_adjustment (GTK_RANGE (g_qeglobals_gui.d_texture_scroll));
1711   gtk_signal_connect (GTK_OBJECT (vadjustment), "value_changed", GTK_SIGNAL_FUNC (vertical_scroll), this);
1712
1713   if (g_PrefsDlg.m_bTextureScrollbar)
1714     gtk_widget_show (g_qeglobals_gui.d_texture_scroll);
1715   else
1716     gtk_widget_hide (g_qeglobals_gui.d_texture_scroll);
1717   m_bNeedRange = true;
1718
1719   gtk_signal_connect (GTK_OBJECT (m_pFilter), "changed", GTK_SIGNAL_FUNC (filter_changed), this);
1720   if (g_PrefsDlg.m_bTextureWindow)
1721     gtk_widget_show (m_pFilter);
1722 }
1723
1724 void TexWnd::UpdateFilter(const char* pFilter)
1725 {
1726   g_bFilterEnabled = false;
1727   if (pFilter)
1728   {
1729     g_strFilter = pFilter;
1730     if (g_strFilter.GetLength() > 0)
1731       g_bFilterEnabled = true;
1732     QERApp_SortActiveShaders();
1733   }
1734   Sys_UpdateWindows (W_TEXTURE);
1735 }
1736
1737 void TexWnd::OnSize (int cx, int cy)
1738 {
1739   m_bNeedRange = true;
1740 }
1741
1742 void TexWnd::OnExpose ()
1743 {
1744   int nOld = g_qeglobals.d_texturewin.m_nTotalHeight;
1745   if (!MakeCurrent ())
1746   {
1747     Sys_Printf("ERROR: glXMakeCurrent failed..\n ");
1748     Sys_Printf("Please restart Radiant if the Texture view is not working\n");
1749   } else
1750   {
1751     QE_CheckOpenGLForErrors();
1752     Texture_Draw (m_pWidget->allocation.width, m_pWidget->allocation.height - g_nTextureOffset);
1753     QE_CheckOpenGLForErrors();
1754     SwapBuffers ();
1755   }
1756   if (g_PrefsDlg.m_bTextureScrollbar && (m_bNeedRange || g_qeglobals.d_texturewin.m_nTotalHeight != nOld))
1757   {
1758     GtkAdjustment *vadjustment = gtk_range_get_adjustment (GTK_RANGE (g_qeglobals_gui.d_texture_scroll));
1759
1760     vadjustment->value = -g_qeglobals.d_texturewin.originy;
1761     vadjustment->page_size = m_pWidget->allocation.height;
1762     vadjustment->page_increment = m_pWidget->allocation.height/2;
1763     vadjustment->step_increment = 20;
1764     vadjustment->lower = 0;
1765     vadjustment->upper = g_qeglobals.d_texturewin.m_nTotalHeight;
1766
1767     gtk_signal_emit_by_name (GTK_OBJECT (vadjustment), "changed");
1768
1769     m_bNeedRange = false;
1770   }
1771 }
1772
1773 void TexWnd::OnLButtonDown (guint32 flags, int pointx, int pointy)
1774 {
1775   SetCapture ();
1776   Texture_MouseDown (pointx, pointy - g_nTextureOffset, flags);
1777 }
1778
1779 void TexWnd::OnRButtonDown (guint32 flags, int pointx, int pointy)
1780 {
1781   SetCapture ();
1782   Texture_MouseDown (pointx, pointy - g_nTextureOffset, flags);
1783 }
1784
1785 void TexWnd::OnMButtonDown (guint32 flags, int pointx, int pointy)
1786 {
1787   SetCapture ();
1788   Texture_MouseDown (pointx, pointy - g_nTextureOffset, flags);
1789 }
1790
1791 void TexWnd::OnLButtonUp (guint32 flags, int pointx, int pointy)
1792 {
1793   ReleaseCapture ();
1794   // NOTE TTimo http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=23
1795   DragDropTexture (flags, pointx, pointy);
1796 }
1797
1798 void TexWnd::OnRButtonUp (guint32 flags, int pointx, int pointy)
1799 {
1800   ReleaseCapture ();
1801 }
1802
1803 void TexWnd::OnMButtonUp (guint32 flags, int pointx, int pointy)
1804 {
1805   ReleaseCapture ();
1806 }
1807
1808 void TexWnd::OnMouseMove (guint32 flags, int pointx, int pointy)
1809 {
1810   Texture_MouseMoved (pointx, pointy - g_nTextureOffset, flags);
1811   // if scrollbar is hidden, we don't seem to get an update
1812   if( !g_PrefsDlg.m_bTextureScrollbar )
1813     RedrawWindow ();
1814 }
1815
1816 void TexWnd::OnVScroll ()
1817 {
1818   GtkAdjustment *vadjustment = gtk_range_get_adjustment (GTK_RANGE (g_qeglobals_gui.d_texture_scroll));
1819
1820   g_qeglobals.d_texturewin.originy = - (int)vadjustment->value;
1821   RedrawWindow ();
1822 }
1823
1824 void TexWnd::UpdatePrefs()
1825 {
1826   if (g_PrefsDlg.m_bTextureWindow)
1827     gtk_widget_show (m_pFilter);
1828   else
1829     gtk_widget_hide (m_pFilter);
1830
1831   if (g_PrefsDlg.m_bTextureScrollbar)
1832     gtk_widget_show (g_qeglobals_gui.d_texture_scroll);
1833   else
1834     gtk_widget_hide (g_qeglobals_gui.d_texture_scroll);
1835   m_bNeedRange = true;
1836   RedrawWindow ();
1837 }
1838
1839 void TexWnd::FocusEdit()
1840 {
1841   if (GTK_WIDGET_VISIBLE (m_pFilter))
1842     gtk_window_set_focus (GTK_WINDOW (g_pParentWnd->m_pWidget), m_pFilter);
1843 }
1844
1845 void TexWnd::OnMouseWheel(bool bUp)
1846 {
1847   if (bUp)
1848   {
1849     if(g_qeglobals.d_texturewin.originy < 0) {
1850       g_qeglobals.d_texturewin.originy += g_PrefsDlg.m_nWheelInc;
1851       // clamp so we don't get jiggle if moved by less than scrollwheel increment
1852       if(g_qeglobals.d_texturewin.originy > 0) {
1853         g_qeglobals.d_texturewin.originy = 0;
1854       }
1855     }
1856   }
1857   else
1858   {
1859     if(g_qeglobals.d_texturewin.originy > (-g_qeglobals.d_texturewin.m_nTotalHeight + g_qeglobals.d_texturewin.height))
1860       g_qeglobals.d_texturewin.originy -= g_PrefsDlg.m_nWheelInc;
1861   }
1862   GtkAdjustment *vadjustment = gtk_range_get_adjustment (GTK_RANGE (g_qeglobals_gui.d_texture_scroll));
1863   gtk_adjustment_set_value (vadjustment, abs(g_qeglobals.d_texturewin.originy));
1864
1865   RedrawWindow();
1866 }
1867
1868 // NOTE TTimo
1869 // http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=23
1870 void TexWnd::DragDropTexture (guint32 flags, int pointx, int pointy)
1871 {
1872   // This gets called from leftmouse up event. We see if the mouseup is above
1873   // the camwindow. If this is the case do a trace for a surface. If we hit a
1874   // surface, texture it with the current texture.
1875
1876   int     m_ptXcheck, m_ptYcheck;
1877   int     m_ptX, m_ptY;
1878   GtkWidget *widget;
1879   gint x, y;
1880   vec3_t  dir;
1881   float   f, r, u;
1882   int     i;
1883
1884   // we only want to catch a plain mouseevent
1885   if (flags)
1886     return;
1887
1888   // see if we are above the camwindow
1889   Sys_GetCursorPos (&m_ptX, &m_ptY);
1890
1891   if (g_pParentWnd->CurrentStyle() == MainFrame::eFloating)
1892     widget = g_pParentWnd->GetCamWnd()->m_pParent;
1893   else
1894     widget = g_pParentWnd->GetCamWnd()->GetWidget();
1895
1896   get_window_pos (widget, &x, &y);
1897
1898   if (m_ptX < x || m_ptY < y ||
1899       m_ptX > x + widget->allocation.width ||
1900       m_ptY > y + widget->allocation.height)
1901     return;
1902
1903   // check if the camwindow isn't being partially hidden by another window at this point
1904   // http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=187
1905   m_ptXcheck = m_ptX;
1906   m_ptYcheck = m_ptY;
1907
1908   if( g_pParentWnd->GetCamWnd()->GetWidget()->window != gdk_window_at_pointer( &m_ptXcheck, &m_ptYcheck ) )
1909     return;
1910
1911   // calc ray direction
1912   x = m_ptX - x;
1913   y = g_pParentWnd->GetCamWnd()->Camera()->height - 1 - (m_ptY - y);
1914   u = (float)( y - ( g_pParentWnd->GetCamWnd()->Camera()->height * .5f ) ) / ( g_pParentWnd->GetCamWnd()->Camera()->height * .5f );
1915   r = (float)( x - ( g_pParentWnd->GetCamWnd()->Camera()->width * .5f ) ) / ( g_pParentWnd->GetCamWnd()->Camera()->width * .5f );
1916   f = 1;
1917
1918   for (i=0 ; i<3 ; i++)
1919     dir[i] = g_pParentWnd->GetCamWnd()->Camera()->vpn[i] * f +
1920         g_pParentWnd->GetCamWnd()->Camera()->vright[i] * r +
1921         g_pParentWnd->GetCamWnd()->Camera()->vup[i] * u;
1922   VectorNormalize (dir, dir);
1923
1924   // do a trace for a surface
1925         trace_t t;
1926
1927         t = Test_Ray (g_pParentWnd->GetCamWnd()->Camera()->origin, dir, SF_SINGLEFACE);
1928
1929   if (t.brush)
1930   {
1931     texdef_t  tex;
1932     brushprimit_texdef_t brushprimit_tex;
1933
1934     memset (&tex, 0, sizeof(tex));
1935     memset (&brushprimit_tex, 0, sizeof(brushprimit_tex));
1936     if (g_qeglobals.m_bBrushPrimitMode)
1937     {
1938       // brushprimit fitted to a 2x2 texture
1939       brushprimit_tex.coords[0][0] = 1.0f;
1940       brushprimit_tex.coords[1][1] = 1.0f;
1941     } else
1942     {
1943       tex.scale[0] = g_pGameDescription->mTextureDefaultScale;
1944       tex.scale[1] = g_pGameDescription->mTextureDefaultScale;
1945     }
1946     tex.flags = g_qeglobals.d_texturewin.texdef.flags;
1947     tex.value = g_qeglobals.d_texturewin.texdef.value;
1948     tex.contents = g_qeglobals.d_texturewin.texdef.contents;
1949     // TTimo - shader code cleanup
1950     // texdef.name is the name of the shader, not the name of the actual texture file
1951     tex.SetName(g_qeglobals.d_texturewin.texdef.GetName());
1952
1953     Undo_Start("set face textures");
1954           Undo_AddBrush(t.brush);
1955           SetFaceTexdef (t.face, &tex, &brushprimit_tex, false, NULL );
1956           Brush_Build(t.brush, false);
1957           Undo_EndBrush(t.brush);
1958           Undo_End();
1959
1960     Sys_UpdateWindows (W_CAMERA);
1961     g_pParentWnd->OnTimer ();
1962   }
1963 }