Subversion Repositories Games.Chess Giants

Rev

Rev 2 | Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
1 pmbaty 1
// render.cpp
2
 
3
// thanks ChaotikMind for optimizing the engine a bit :)
4
 
5
#include "common.h"
6
 
7
 
8
// note: DirectX requires a C++ compiler.
9
#include "DirectX9/Include/d3d9.h"
10
#include "DirectX9/Include/d3dx9.h"
11
 
12
// include the Direct3D library files
13
#pragma comment (lib, "DirectX9/Lib/x86/d3d9.lib")
14
#pragma comment (lib, "DirectX9/Lib/x86/d3dx9.lib")
15
 
16
 
17
// define this to display framerate
18
#define WANT_FRAMERATE
19
 
20
 
21
// handy macro to print a chatter channel reply
22
#define PRINT_CCREPLY(ccreply) \
23
{ \
24
   Render_wprintf (rect.right, initial_height - combined_height, initial_width - rect.right, ALIGN_LEFT, ALIGN_TOP, ALIGN_LEFT, \
25
                   chat_fontindex, (ccreply)->color, &rect, \
26
                   L"["); \
27
   Render_wprintf (rect.right, initial_height - combined_height, initial_width - rect.right, ALIGN_LEFT, ALIGN_TOP, ALIGN_LEFT, \
28
                   chat_fontindex, RGBA_TO_RGBACOLOR (159, 159, 159, RGBACOLOR_ALPHA ((ccreply)->color)), &rect, \
29
                   (ccreply)->channelname); \
30
   Render_wprintf (rect.right, initial_height - combined_height, initial_width - rect.right, ALIGN_LEFT, ALIGN_TOP, ALIGN_LEFT, \
31
                   chat_fontindex, (ccreply)->color, &rect, \
32
                   L"] "); /* closing bracket + non-breakable space */ \
33
   Render_wprintf (rect.right, initial_height - combined_height, initial_width - rect.right, ALIGN_LEFT, ALIGN_TOP, ALIGN_LEFT, \
34
                   chat_fontindex, RGBA_TO_RGBACOLOR (159, 159, 159, RGBACOLOR_ALPHA ((ccreply)->color)), &rect, \
35
                   (ccreply)->nickname); \
36
   Render_wprintf (rect.right, initial_height - combined_height, initial_width - rect.right, ALIGN_LEFT, ALIGN_TOP, ALIGN_LEFT, \
37
                   chat_fontindex, (ccreply)->color, &rect, \
38
                   L": "); /* colon + non-breakable space */ \
39
   if ((ccreply)->text != NULL) \
40
      Render_wprintf (rect.right, initial_height - combined_height, initial_width - rect.right, ALIGN_LEFT, ALIGN_TOP, ALIGN_LEFT, \
41
                      chat_fontindex, (ccreply)->color, &rect, \
42
                      (ccreply)->text); \
43
}
44
 
45
 
46
// handy macro to draw a GUI button
47
#define DRAW_BUTTON_IF_NEEDED(button) \
48
{ \
49
   if ((button).state != 0) \
50
      Render_DrawSprite (&sprites[(button).sprite_index], (button).left, (button).top, (button).width, (button).height, ((button).state == 2 ? 0xFF : 0x7F)); \
51
}
52
 
53
 
54
// handy macro to draw a GUI text
55
#define DRAW_TEXT_IF_NEEDED(text) \
56
{ \
57
   if ((text).is_displayed) \
58
   { \
59
      Render_wprintf ((int) ((text).xpos_percent * (float) initial_width) / 100, (int) ((text).ypos_percent * (float) initial_height) / 100, \
60
                      (int) ((text).maxwidth_percent * (float) initial_width) / 100, (text).horizontal_align, (text).vertical_align, (text).text_align, (text).font_index, \
61
                      ((text).want_fade ? \
62
                       RGBACOLOR_SETALPHA ((text).color, \
63
                                           (((text).appear_time + (text).disappear_time) * 0.5f > current_time ? \
64
                                           /* fading in  */ (int) FadeFloat (0, RGBACOLOR_ALPHA ((text).color), (text).appear_time, (text).appear_time + 0.5f) : \
65
                                           /* fading out */ (int) FadeFloat (RGBACOLOR_ALPHA ((text).color), 0, (text).disappear_time - 3.0f, (text).disappear_time))) : \
66
                       (text).color), \
67
                      NULL, (text).buffer); \
68
      if ((text).disappear_time < current_time) \
69
         (text).is_displayed = false; \
70
   } \
71
}
72
 
73
 
74
#pragma pack(push,1)
75
 
76
// definition for a vector
77
typedef struct vector_s
78
{
79
   float x; // X component
80
   float y; // Y component
81
   float z; // Z component
82
} vector_t;
83
 
84
 
85
// definition for a texture coordinates pair
86
typedef struct texcoord_s
87
{
88
   float u; // X coordinate of the texture point this vertex corresponds to
89
   float v; // Y coordinate of the texture point this vertex corresponds to
90
} texcoord_t;
91
 
92
 
93
// definition for a vertex (must be in that order for Direct3D)
94
typedef struct vertex_s
95
{
96
   vector_t position; // position in space
97
   vector_t normal; // coordinates of the unary normal vector of the plane this vertex is on (for illumination)
98
   texcoord_t texcoord; // coordinates of the texture point this vertex corresponds to
99
} vertex_t;
100
 
101
#pragma pack(pop)
102
 
103
 
104
// definition for a reflected object (qsort array element to sort reflections by distance)
105
typedef struct reflectedobject_s
106
{
107
   sceneobject_t *object; // pointer to the scene object
108
   float distance; // distance to viewer camera
109
} reflectedobject_t;
110
 
111
 
112
// definition for a material (light reflection type)
113
typedef struct material_s
114
{
115
   wchar_t name[32]; // material name
116
   float ambient; // ambient reflection value ranging from 0 to 1
117
   float diffuse; // diffuse reflection value ranging from 0 to 1
118
   float emissive; // emissive reflection value ranging from 0 to 1
119
   float specular; // specular reflection value ranging from 0 to 1
120
   float shininess; // shininess (specular factor)
121
   float transparency; // transparency value ranging from 0 (fully transparent) to 1 (opaque)
122
} material_t;
123
 
124
 
125
// definition for a mesh
126
typedef struct mesh_s
127
{
128
   unsigned long hash; // basic content hash, to avoid duplicates
129
   unsigned long vertex_format;
130
   IDirect3DVertexBuffer9 *d3dvertices; // handled opaquely by Direct3D
131
   int vertice_size;
132
   int vertice_count;
133
   bool is_indexed; // set to TRUE if this mesh has an index buffer
134
   IDirect3DIndexBuffer9 *d3dindices; // handled opaquely by Direct3D
135
   int indice_size;
136
   int indice_count;
137
} mesh_t;
138
 
139
 
140
// definition for a texture
141
typedef struct texture_s
142
{
143
   unsigned long hash; // basic content hash, to avoid duplicates
144
   int width;
145
   int height;
146
   IDirect3DTexture9 *texture;
147
} texture_t;
148
 
149
 
150
// definition for a font
151
typedef struct font_s
152
{
153
   unsigned long pathname_hash;
154
   ID3DXFont *font;
155
} font_t;
156
 
157
 
158
// definition for a sprite
159
typedef struct sprite_s
160
{
161
   unsigned long hash; // basic content hash, to avoid duplicates
162
   ID3DXSprite *sprite;
163
   int texture_index;
164
} sprite_t;
165
 
166
 
167
// global variables used in this module only
168
static IDirect3D9 *d3d = NULL; // our Direct3D interface
169
static IDirect3DDevice9 *d3ddev = NULL; // the device class
170
 
171
static material_t *materials = NULL;
172
static int material_count = 0;
173
static texture_t *textures = NULL;
174
static int texture_count = 0;
175
static mesh_t *meshes = NULL;
176
static int mesh_count = 0;
177
static font_t *fonts = NULL;
178
static int font_count = 0;
179
static sprite_t *sprites = NULL;
180
static int sprite_count = 0;
181
static const float fov_value = 45.0f; // field of view width, in degrees
182
static const float viewdist_near = 1.0f; // nearest view plane distance
183
static const float viewdist_far = 200.0f; // farthest view plane distance
184
static int initial_width = 0; // initial width of the render surface, in pixels
185
static int initial_height = 0; // initial height of the render surface, in pixels
186
static float current_width = 0.0f; // current width of the client area on which the render surface is rendered, in pixels
187
static float current_height = 0.0f; // current height of the client area on which the render surface is rendered, in pixels
188
static D3DCOLOR ambient_light;
189
static vector_t camera_position;
190
static const vector_t scene_center = { 0.0f, 0.0f, 0.0f };
191
static const vector_t upwards_direction = { 0.0f, 0.0f, 1.0f };
192
static int best_supported_filter;
193
static unsigned long multisample_quality = 0;
194
 
195
static wchar_t printf_buffer[0xffff];
196
 
197
 
198
// prototypes of functions used in this module only
199
static bool Render_LoadMesh_X (mesh_t *mesh, const wchar_t *xfile_pathname);
200
static bool Render_LoadMesh_Obj (mesh_t *mesh, const wchar_t *objfile_pathname);
201
static void Render_DrawSceneObjectReflection (sceneobject_t *sceneobject);
202
static void Render_DrawSceneObject (sceneobject_t *sceneobject);
203
static void Render_DrawSceneTile (sceneobject_t *sceneobject);
204
static void Render_DrawSprite (sprite_t *sprite, float x_percent, float y_percent, float width_percent, float height_percent, int alpha);
205
static void Render_GetTextBoundaries (int max_width, int font_id, wchar_t *text, RECT *rect);
206
static void Render_wprintf (int x, int y, int max_width, int horiz_align, int vert_align, int text_align, int font_id, unsigned long color_rgba, RECT *out_rect, const wchar_t *fmt, ...);
207
static float DistanceToCamera (float x, float y, float z);
208
static float FadeFloat (float from, float to, float start_time, float end_time);
209
static unsigned long HashString (const wchar_t *string_buffer);
210
static unsigned long HashFile (const wchar_t *file_pathname);
211
static void ResolveWildcard (wchar_t *file_pathname, wchar_t *extensions_separated_by_bars);
212
static int SortReflectedObjects (const void *object1, const void *object2);
213
 
214
 
215
bool Render_Init (void)
216
{
217
   // this function sets up and initializes Direct3D
218
 
219
   static wchar_t *default_materialname = L"default";
220
 
221
   D3DCAPS9 device_capabilities;
222
   unsigned long behaviour_flags;
223
   unsigned long best_multisample_type;
224
   D3DPRESENT_PARAMETERS d3dpp;
225
   wchar_t line_buffer[256];
226
   material_t material;
227
   RECT rect;
228
   FILE *fp;
229
 
230
   // create the Direct3D interface
231
MessageBox (NULL, L"about to call Direct3dCreate9()", L"info", MB_OK);
232
   d3d = Direct3DCreate9 (D3D_SDK_VERSION);
233
MessageBox (NULL, L"Direct3dCreate9() call returned", L"info", MB_OK);
234
 
235
   // get hardware capabilities
236
   if (FAILED (d3d->GetDeviceCaps (D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, &device_capabilities)))
237
   {
238
      MessageBox (NULL, LOCALIZE (L"Error_CouldNotCreateD3DDevGetDeviceCapsFailed"), LOCALIZE (L"FatalError"), MB_ICONERROR | MB_OK);
239
      return (false);
240
   }
241
MessageBox (NULL, L"GetDeviceCaps() call returned", L"info", MB_OK);
242
 
243
   // grab info from that and adjust our D3D settings
244
   best_supported_filter = (device_capabilities.RasterCaps & D3DPRASTERCAPS_ANISOTROPY ? D3DTEXF_ANISOTROPIC : D3DTEXF_LINEAR);
245
   behaviour_flags = (device_capabilities.VertexProcessingCaps != 0 ? D3DCREATE_HARDWARE_VERTEXPROCESSING : D3DCREATE_SOFTWARE_VERTEXPROCESSING);
246
 
247
   // see if full-scene antialiasing is supported and pick the best available multisample type
248
   best_multisample_type = D3DMULTISAMPLE_NONE;
249
   while (SUCCEEDED (d3d->CheckDeviceMultiSampleType (D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, D3DFMT_X8R8G8B8, false, (D3DMULTISAMPLE_TYPE) (best_multisample_type + 1), &multisample_quality)))
250
   {
251
      best_multisample_type++; // increase multisample type as long as the next one is supported
252
      if ((best_multisample_type == D3DMULTISAMPLE_2_SAMPLES) && !options.want_hiquality)
253
         break; // stop searching for the best one if we don't want the highest possible quality
254
   }
255
MessageBox (NULL, L"CheckDeviceMultiSampleType() call returned", L"info", MB_OK);
256
 
257
   memset (&d3dpp, 0, sizeof (d3dpp)); // clear out the struct for use
258
   d3dpp.Windowed = true; // always windowed (because we can't display dialog boxes in fullscreen mode)
259
   d3dpp.BackBufferCount = 1;
260
   d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; // discard old frames
261
   d3dpp.hDeviceWindow = hMainWnd; // set the window to be used by Direct3D
262
   d3dpp.EnableAutoDepthStencil = true; // enable Z-buffer and stencil buffer
263
   d3dpp.AutoDepthStencilFormat = D3DFMT_D24S8; // D3DFMT_D15S1 15 bits should be enough to store each pixel's Z depth
264
   d3dpp.MultiSampleType = (D3DMULTISAMPLE_TYPE) best_multisample_type; // use multisampling (full scene antialiasing) if supported
265
   d3dpp.MultiSampleQuality = (multisample_quality > 0 ? multisample_quality - 1 : 0);
266
 
267
   // create a device class using this information and the info from the d3dpp stuct
268
   if (FAILED (d3d->CreateDevice (D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hMainWnd, behaviour_flags, &d3dpp, &d3ddev)))
269
   {
270
      MessageBox (NULL, LOCALIZE (L"Error_CouldNotCreateD3DDevCreateDeviceFailed"), LOCALIZE (L"FatalError"), MB_ICONERROR | MB_OK);
271
      return (false);
272
   }
273
MessageBox (NULL, L"CreateDevice() call returned", L"info", MB_OK);
274
 
275
   // get the device view port and save the initial width and height
276
   GetClientRect (hMainWnd, &rect);
277
   initial_width = rect.right; // they may differ from window width and window height
278
   initial_height = rect.bottom; // because of title bars, menus, borders, etc.
279
 
280
   // set the texture parameters
281
   d3ddev->SetSamplerState (0, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP); // wrap textures around their edges
282
   d3ddev->SetSamplerState (0, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP);
283
   d3ddev->SetTextureStageState (0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); // and modulate their alpha with the material's alpha
284
   d3ddev->SetTextureStageState (0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE);
285
   d3ddev->SetTextureStageState (0, D3DTSS_ALPHAOP, D3DTOP_MODULATE);
286
 
287
   // enable the Z buffer
288
   d3ddev->SetRenderState (D3DRS_ZENABLE, true);
289
 
290
   // disable the stencil buffer
291
   d3ddev->SetRenderState (D3DRS_STENCILENABLE, false);
292
 
293
   // normalize the face normals (if we don't, scaling will cause problems with lighting computations)
294
   d3ddev->SetRenderState (D3DRS_NORMALIZENORMALS, true);
295
 
296
   // turn on alpha blending
297
   d3ddev->SetRenderState (D3DRS_ALPHABLENDENABLE, true);
298
   d3ddev->SetRenderState (D3DRS_BLENDOP, D3DBLENDOP_ADD);
299
   d3ddev->SetRenderState (D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
300
   d3ddev->SetRenderState (D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
301
 
302
   // use all of the materials' light reflection properties
303
   d3ddev->SetRenderState (D3DRS_AMBIENTMATERIALSOURCE, D3DMCS_MATERIAL);
304
   d3ddev->SetRenderState (D3DRS_DIFFUSEMATERIALSOURCE, D3DMCS_MATERIAL);
305
   d3ddev->SetRenderState (D3DRS_SPECULARMATERIALSOURCE, D3DMCS_MATERIAL);
306
   d3ddev->SetRenderState (D3DRS_EMISSIVEMATERIALSOURCE, D3DMCS_MATERIAL);
307
   d3ddev->SetRenderState (D3DRS_COLORVERTEX, false);
308
 
309
   // enable 3D lighting
310
   d3ddev->SetRenderState (D3DRS_LIGHTING, true);
311
MessageBox (NULL, L"SetRenderState() calls returned", L"info", MB_OK);
312
 
313
   // open and parse the materials file and build the materials list
314
   materials = NULL;
315
   material_count = 0;
316
   _wfopen_s (&fp, L"materials.cfg", L"r, ccs=UNICODE");
317
   if (fp != NULL)
318
   {
319
      // read line per line...
320
      while (fgetws (line_buffer, WCHAR_SIZEOF (line_buffer), fp) != NULL)
321
      {
322
         // can we read a complete material line ?
323
         if (swscanf_s (line_buffer, L"\"%[^\"]\" %f %f %f %f %f %f", material.name, WCHAR_SIZEOF (material.name), &material.ambient, &material.diffuse, &material.emissive, &material.specular, &material.shininess, &material.transparency) == 7)
324
         {
325
            materials = (material_t *) SAFE_realloc (materials, material_count, material_count + 1, sizeof (material_t), false);
326
            memcpy (&materials[material_count], &material, sizeof (material_t));
327
            material_count++; // if so, append this new material to the materials array
328
         }
329
      }
330
      fclose (fp); // finished, close the file
331
   }
332
   materials = (material_t *) SAFE_realloc (materials, material_count, material_count + 1, sizeof (material_t), false);
333
   wcscpy_s (materials[material_count].name, WCHAR_SIZEOF (materials[material_count].name), default_materialname);
334
   materials[material_count].ambient = 1.0f;
335
   materials[material_count].diffuse = 1.0f;
336
   materials[material_count].emissive = 0.0f;
337
   materials[material_count].specular = 0.0f;
338
   materials[material_count].shininess = 0.0f;
339
   materials[material_count].transparency = 1.0f;
340
   material_count++; // append a default material at the end of the array and we're all set
341
 
342
   return (true); // finished
343
}
344
 
345
 
346
void Render_Shutdown (void)
347
{
348
   // this function shuts down the Direct3D interfaces and releases the Direct3D COM objects
349
 
350
   int array_index;
351
 
352
   // close and release font data
353
   SAFE_free ((void **) &fonts);
354
   font_count = 0;
355
 
356
   // close and release sprite data
357
   SAFE_free ((void **) &sprites);
358
   sprite_count = 0;
359
 
360
   // close and release meshes data
361
   if (meshes != NULL)
362
   {
363
      for (array_index = 0; array_index < mesh_count; array_index++)
364
      {
365
         if (meshes[array_index].d3dindices != NULL)
366
            meshes[array_index].d3dindices->Release ();
367
         meshes[array_index].d3dindices = NULL;
368
 
369
         if (meshes[array_index].d3dvertices != NULL)
370
            meshes[array_index].d3dvertices->Release ();
371
         meshes[array_index].d3dvertices = NULL;
372
      }
373
   }
374
   meshes = NULL;
375
   mesh_count = 0;
376
 
377
   // close and release texture data
378
   if (textures != NULL)
379
   {
380
      for (array_index = 0; array_index < texture_count; array_index++)
381
         if (textures[array_index].texture != NULL)
382
            textures[array_index].texture->Release ();
383
      SAFE_free ((void **) &textures);
384
   }
385
   texture_count = 0;
386
 
387
   // close and release materials data
388
   SAFE_free ((void **) &materials);
389
   material_count = 0;
390
 
391
   // close and release the 3D device
392
   if (d3ddev != NULL)
393
      d3ddev->Release ();
394
   d3ddev = NULL;
395
 
396
   // close and release Direct3D
397
   if (d3d != NULL)
398
      d3d->Release ();
399
   d3d = NULL;
400
 
401
   return; // finished
402
}
403
 
404
 
405
void Render_RenderFrame (scene_t *scene)
406
{
407
   // this is the function used to render a single frame
408
 
409
   static int framerate_value = 0;
410
   static int framerate_count = 0;
411
   static float framerate_time = 0;
412
 
413
   D3DXMATRIX scaling_matrix;
414
   D3DXMATRIX translation_matrix;
415
   D3DXMATRIX view_matrix; // the view transform matrix
416
   D3DXMATRIX projection_matrix; // the projection transform matrix
417
   D3DLIGHT9 dxlight;
418
   RECT rect;
419
   float angle;
420
   float sin_pitch;
421
   float sin_yaw;
422
   float cos_pitch;
423
   float cos_yaw;
424
   int light_index;
425
   int object_index;
426
   int cchistory_index;
427
   int cchistory_index2;
428
   int combined_width;
429
   int combined_height;
430
   light_t *light;
431
   ccreply_t *ccreply;
432
   sceneobject_t *sceneobject;
433
   reflectedobject_t *reflectedobjects; // mallocated
434
   int reflectedobject_count;
435
   reflectedobject_t *otherobjects; // mallocated
436
   int otherobject_count;
437
 
438
   // get the device view port and save the actual width and height
439
   GetClientRect (hMainWnd, &rect);
440
   current_width = (float) rect.right; // they may differ from window width and window height
441
   current_height = (float) rect.bottom; // because of title bars, menus, borders, etc.
442
 
443
   // clear the back buffer, the Z buffer and the stencil buffer
444
   d3ddev->Clear (0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER | D3DCLEAR_STENCIL, D3DCOLOR_XRGB (0, 0, 0), 1.0f, 0);
445
   d3ddev->BeginScene (); // begins the 3D scene
446
 
447
   ////////////////////////////////////////
448
   // Setup scene lights
449
 
450
   // There are three types of light : ambient, diffuse and specular.
451
   // Diffuse lights can be of type directional (sun), point (bulb) or spot (flashlight).
452
 
453
   // The attenuation formula for point lights is :
454
   // Atten = 1 / (att0 + (att1 * d) + (att2 * d²))
455
 
456
   // In spot lights, Phi is the outer cone angle. Theta is the inner cone angle.
457
 
458
   // set the default lighting color
459
   ambient_light = RGBACOLOR_TO_ARGBCOLOR (RGBACOLOR_FULLALPHA (theme->illum.ambient_light));
460
   d3ddev->SetRenderState (D3DRS_AMBIENT, ambient_light);
461
 
462
   // for each light...
463
   for (light_index = 0; light_index < theme->illum.light_count; light_index++)
464
   {
465
      light = &theme->illum.lights[light_index]; // quick access to light
466
 
467
      memset (&dxlight, 0, sizeof (dxlight)); // clear out the dxlight struct for use
468
 
469
      // set its type
470
      if (light->type == LIGHT_DIRECTIONAL)
471
         dxlight.Type = D3DLIGHT_DIRECTIONAL; // directional light (e.g, sun)
472
      else if (light->type == LIGHT_POINT)
473
         dxlight.Type = D3DLIGHT_POINT; // point light (e.g, light bulb)
474
      else if (light->type == LIGHT_SPOT)
475
         dxlight.Type = D3DLIGHT_SPOT; // spot light (e.g, flash light)
476
      else
477
      {
478
         d3ddev->LightEnable (light_index, false); // unknown light ; turn off light #index
479
         continue; // and proceed to the next one
480
      }
481
 
482
      // set its parameters
483
      dxlight.Diffuse = D3DXCOLOR (RGBACOLOR_TO_ARGBCOLOR (RGBACOLOR_FULLALPHA (light->color)));
484
      dxlight.Specular = D3DXCOLOR (0xffffffff);
485
      dxlight.Position.x = light->pos_x;
486
      dxlight.Position.y = light->pos_y;
487
      dxlight.Position.z = light->pos_z;
488
      dxlight.Direction.x = light->direction_x;
489
      dxlight.Direction.y = light->direction_y;
490
      dxlight.Direction.z = light->direction_z;
491
      dxlight.Range = light->range; // light won't be computed after this distance
492
      dxlight.Attenuation0 = light->attenuation_constant; // constant attenuation, see formula
493
      dxlight.Attenuation1 = light->attenuation_proportional; // proportional attenuation, see formula
494
      dxlight.Attenuation2 = light->attenuation_square; // square attenuation, see formula
495
      dxlight.Phi = light->cone_outer * TO_RADIANS; // outer spot cone
496
      dxlight.Theta = light->cone_inner * TO_RADIANS; // inner spot cone
497
 
498
      d3ddev->SetLight (light_index, &dxlight); // send the light struct properties to light #index
499
      d3ddev->LightEnable (light_index, true); // turn on light #index
500
   }
501
 
502
   ////////////////////////////////
503
   // View transform
504
 
505
   // compute the sine and cosine of the pitch component
506
   angle = current_pitch * TO_RADIANS;
507
   sin_pitch = sinf (angle);
508
   cos_pitch = cosf (angle);
509
 
510
   // compute the sine and cosine of the yaw component
511
   angle = current_yaw * TO_RADIANS;
512
   sin_yaw = sinf (angle);
513
   cos_yaw = cosf (angle);
514
 
515
   // build the camera position
516
   camera_position.x = (float) -(cos_pitch * cos_yaw) * current_distance;
517
   camera_position.y = (float) -(cos_pitch * sin_yaw) * current_distance;
518
   camera_position.z = (float) sin_pitch * current_distance;
519
 
520
   // set up a view matrix
521
   D3DXMatrixLookAtLH (&view_matrix,
522
                       (D3DXVECTOR3 *) &camera_position, // camera position
523
                       (D3DXVECTOR3 *) &scene_center, // look-at position
524
                       (D3DXVECTOR3 *) &upwards_direction); // up direction
525
 
526
   // tell Direct3D about our matrix
527
   d3ddev->SetTransform (D3DTS_VIEW, &view_matrix);
528
 
529
   /////////////////////////////////////
530
   // Projection transform
531
 
532
   // set up a projection matrix
533
   D3DXMatrixPerspectiveFovLH (&projection_matrix,
534
                               fov_value * TO_RADIANS, // field of view width
535
                               current_width / current_height, // aspect ratio
536
                               viewdist_near, viewdist_far); // view plane distances
537
 
538
   // tell Direct3D about our matrix
539
   d3ddev->SetTransform (D3DTS_PROJECTION, &projection_matrix);
540
 
541
   /////////////////////////////////////
542
   // End of the transforms
543
 
544
   // if we want it, enable specular lighting
545
   d3ddev->SetRenderState (D3DRS_SPECULARENABLE, options.want_specularlighting);
546
 
547
   // turn on texture filtering if needed
548
   if (options.want_filtering)
549
   {
550
      d3ddev->SetSamplerState (0, D3DSAMP_MINFILTER, best_supported_filter);
551
      d3ddev->SetSamplerState (0, D3DSAMP_MAGFILTER, best_supported_filter);
552
      d3ddev->SetSamplerState (0, D3DSAMP_MIPFILTER, D3DTEXF_LINEAR);
553
 
554
      // turn on fullscene antialiasing only if capable
555
      d3ddev->SetRenderState (D3DRS_MULTISAMPLEANTIALIAS, (multisample_quality > 0));
556
   }
557
   else
558
   {
559
      d3ddev->SetSamplerState (0, D3DSAMP_MINFILTER, D3DTEXF_NONE);
560
      d3ddev->SetSamplerState (0, D3DSAMP_MAGFILTER, D3DTEXF_NONE);
561
      d3ddev->SetSamplerState (0, D3DSAMP_MIPFILTER, D3DTEXF_NONE);
562
 
563
      // turn off fullscene antialiasing
564
      d3ddev->SetRenderState (D3DRS_MULTISAMPLEANTIALIAS, false);
565
   }
566
 
567
   /////////////////////////////////////////////////////////////
568
   // draw the background elements. No need for a Z buffer here.
569
 
570
   d3ddev->SetRenderState (D3DRS_ZENABLE, false); // disable depth testing
571
 
572
   // draw the background sprite, if any
573
   if (scene->background_spriteindex >= 0)
574
      Render_DrawSprite (&sprites[scene->background_spriteindex], 0.0f, 0.0f, 100.0f, 100.0f, 0xFF);
575
 
576
   // draw the table border
577
   Render_DrawSceneObject (&scene->objects[0]);
578
   Render_DrawSceneObject (&scene->objects[1]);
579
 
580
   // draw the table and build the stencil buffer at the same time
581
   d3ddev->SetRenderState (D3DRS_STENCILENABLE, true); // enable the stencil buffer (i.e. the "frame" for drawing table reflections)
582
   d3ddev->SetRenderState (D3DRS_STENCILFUNC, D3DCMP_ALWAYS); // instruct how to fill it
583
   d3ddev->SetRenderState (D3DRS_STENCILPASS, D3DSTENCILOP_INCRSAT); // instruct how to fill it
584
   Render_DrawSceneObject (&scene->objects[2]); // draw the table squares in the stencil buffer
585
   d3ddev->SetRenderState (D3DRS_STENCILENABLE, false); // finished drawing the stencil buffer
586
 
587
   d3ddev->SetRenderState (D3DRS_ZENABLE, true); // re-enable depth testing
588
 
589
   ////////////////////////////////////////////////////////////
590
   // draw the scene objects and their reflections on the table
591
 
592
   // start with the reflections if we want them, and if the table does it
593
   if (options.want_reflections && (theme->reflection_alpha > 0))
594
   {
595
      // build an array of reflected objects with their distances
596
      reflectedobjects = NULL;
597
      reflectedobject_count = 0;
598
      otherobjects = NULL;
599
      otherobject_count = 0;
600
 
601
      // cycle through all parts and see which ones need to be reflected
602
      for (object_index = 3; object_index < scene->object_count; object_index++)
603
      {
604
         sceneobject = &scene->objects[object_index]; // quick access to scene object
605
 
606
         // is this object a mesh AND it's above the ground ?
607
         if ((sceneobject->mesh_index != -1) && (sceneobject->z > 0))
608
         {
609
            // yes it is. It thus needs to be reflected, so add it to the list
610
            reflectedobjects = (reflectedobject_t *) SAFE_realloc (reflectedobjects, reflectedobject_count, reflectedobject_count + 1, sizeof (reflectedobject_t), false);
611
            reflectedobjects[reflectedobject_count].object = sceneobject; // save scene object
612
            reflectedobjects[reflectedobject_count].distance = DistanceToCamera (sceneobject->x, sceneobject->y, sceneobject->z);
613
            reflectedobject_count++; // we have now one object more to reflect
614
         }
615
         else
616
         {
617
            // no it's not. It doesn't need to be reflected, so add it to the other list
618
            otherobjects = (reflectedobject_t *) SAFE_realloc (otherobjects, otherobject_count, otherobject_count + 1, sizeof (reflectedobject_t), false);
619
            otherobjects[otherobject_count].object = sceneobject; // save scene object
620
            otherobjects[otherobject_count].distance = 0;
621
            otherobject_count++; // we have now one object more to reflect
622
         }
623
      }
624
 
625
      // now sort them from farthest to closest and draw them in this order
626
      qsort (reflectedobjects, reflectedobject_count, sizeof (reflectedobject_t), SortReflectedObjects);
627
      for (object_index = 0; object_index < reflectedobject_count; object_index++)
628
         Render_DrawSceneObjectReflection (reflectedobjects[object_index].object); // draw the reflection
629
      for (object_index = 0; object_index < reflectedobject_count; object_index++)
630
         Render_DrawSceneObject (reflectedobjects[object_index].object); // and draw the objects afterwards
631
      for (object_index = 0; object_index < otherobject_count; object_index++)
632
         Render_DrawSceneObject (otherobjects[object_index].object); // finally, draw the non-reflected objects
633
 
634
      SAFE_free ((void **) &reflectedobjects); // and free the reflected objects array
635
      SAFE_free ((void **) &otherobjects); // and the non-reflected objects array
636
   }
637
   else
638
      for (object_index = 3; object_index < scene->object_count; object_index++)
639
         Render_DrawSceneObject (&scene->objects[object_index]); // else if no reflections, draw the objects, the Z-buffer will sort them
640
 
641
   // draw the overlay texture if required
642
   if (scene->overlay_spriteindex >= 0)
643
      Render_DrawSprite (&sprites[scene->overlay_spriteindex], 0.0f, 0.0f, 100.0f, 100.0f, 0x4F);
644
 
645
   ///////////////
646
   // draw the GUI
647
 
648
   // draw the arrows
649
   DRAW_BUTTON_IF_NEEDED (scene->gui.larrow); // left arrow
650
   DRAW_BUTTON_IF_NEEDED (scene->gui.rarrow); // right arrow
651
   DRAW_TEXT_IF_NEEDED (scene->gui.arrow_text); // arrow text
652
 
653
   if (want_framerate)
654
      Render_wprintf (initial_width - 10, 10, 62, ALIGN_RIGHT, ALIGN_TOP, ALIGN_CENTER, arrow_fontindex, D3DCOLOR_RGBA (255, 255, 255, 255), NULL,
655
                      L"%d textures\n"
656
                      L"%d meshes\n"
657
                      L"%d fonts\n"
658
                      L"%d sprites\n"
659
                      L"%d fps", texture_count, mesh_count, font_count, sprite_count, framerate_value);
660
 
661
   // draw the other GUI buttons
662
   DRAW_BUTTON_IF_NEEDED (scene->gui.chatbutton); // chat button
663
   DRAW_BUTTON_IF_NEEDED (scene->gui.gamesbutton); // games button
664
   DRAW_BUTTON_IF_NEEDED (scene->gui.peoplebutton); // people button
665
 
666
   // does the parts pick line need to be displayed ?
667
   if (scene->gui.is_partspick_displayed)
668
   {
669
#define PARTSIZE_PCT (100.0f / 13.0f)
670
 
671
      if (scene->gui.partspick_selectedpart == 'P')      Render_DrawSprite (&sprites[theme->lastmovetarget_spriteindex],  0.0f * PARTSIZE_PCT, 0.0f, PARTSIZE_PCT, 11.0f, 0xFF);
672
      else if (scene->gui.partspick_selectedpart == 'R') Render_DrawSprite (&sprites[theme->lastmovetarget_spriteindex],  1.0f * PARTSIZE_PCT, 0.0f, PARTSIZE_PCT, 11.0f, 0xFF);
673
      else if (scene->gui.partspick_selectedpart == 'N') Render_DrawSprite (&sprites[theme->lastmovetarget_spriteindex],  2.0f * PARTSIZE_PCT, 0.0f, PARTSIZE_PCT, 11.0f, 0xFF);
674
      else if (scene->gui.partspick_selectedpart == 'B') Render_DrawSprite (&sprites[theme->lastmovetarget_spriteindex],  3.0f * PARTSIZE_PCT, 0.0f, PARTSIZE_PCT, 11.0f, 0xFF);
675
      else if (scene->gui.partspick_selectedpart == 'Q') Render_DrawSprite (&sprites[theme->lastmovetarget_spriteindex],  4.0f * PARTSIZE_PCT, 0.0f, PARTSIZE_PCT, 11.0f, 0xFF);
676
      else if (scene->gui.partspick_selectedpart == 'K') Render_DrawSprite (&sprites[theme->lastmovetarget_spriteindex],  5.0f * PARTSIZE_PCT, 0.0f, PARTSIZE_PCT, 11.0f, 0xFF);
677
      else if (scene->gui.partspick_selectedpart == ' ') Render_DrawSprite (&sprites[theme->lastmovetarget_spriteindex],  6.0f * PARTSIZE_PCT, 0.0f, PARTSIZE_PCT, 11.0f, 0xFF);
678
      else if (scene->gui.partspick_selectedpart == 'k') Render_DrawSprite (&sprites[theme->lastmovetarget_spriteindex],  7.0f * PARTSIZE_PCT, 0.0f, PARTSIZE_PCT, 11.0f, 0xFF);
679
      else if (scene->gui.partspick_selectedpart == 'q') Render_DrawSprite (&sprites[theme->lastmovetarget_spriteindex],  8.0f * PARTSIZE_PCT, 0.0f, PARTSIZE_PCT, 11.0f, 0xFF);
680
      else if (scene->gui.partspick_selectedpart == 'b') Render_DrawSprite (&sprites[theme->lastmovetarget_spriteindex],  9.0f * PARTSIZE_PCT, 0.0f, PARTSIZE_PCT, 11.0f, 0xFF);
681
      else if (scene->gui.partspick_selectedpart == 'n') Render_DrawSprite (&sprites[theme->lastmovetarget_spriteindex], 10.0f * PARTSIZE_PCT, 0.0f, PARTSIZE_PCT, 11.0f, 0xFF);
682
      else if (scene->gui.partspick_selectedpart == 'r') Render_DrawSprite (&sprites[theme->lastmovetarget_spriteindex], 11.0f * PARTSIZE_PCT, 0.0f, PARTSIZE_PCT, 11.0f, 0xFF);
683
      else if (scene->gui.partspick_selectedpart == 'p') Render_DrawSprite (&sprites[theme->lastmovetarget_spriteindex], 12.0f * PARTSIZE_PCT, 0.0f, PARTSIZE_PCT, 11.0f, 0xFF);
684
 
685
      Render_DrawSprite (&sprites[theme->flatsprites[COLOR_WHITE][PART_PAWN]],       0.0f * PARTSIZE_PCT, 0, PARTSIZE_PCT, 11.0f, (((scene->gui.partspick_hoveredpart == 'P') || (scene->gui.partspick_selectedpart == 'P')) ? 0xFF : 0x7F)); // white pawn
686
      Render_DrawSprite (&sprites[theme->flatsprites[COLOR_WHITE][PART_ROOK]],       1.0f * PARTSIZE_PCT, 0, PARTSIZE_PCT, 11.0f, (((scene->gui.partspick_hoveredpart == 'R') || (scene->gui.partspick_selectedpart == 'R')) ? 0xFF : 0x7F)); // white rook
687
      Render_DrawSprite (&sprites[theme->flatsprites[COLOR_WHITE][PART_KNIGHT]],     2.0f * PARTSIZE_PCT, 0, PARTSIZE_PCT, 11.0f, (((scene->gui.partspick_hoveredpart == 'N') || (scene->gui.partspick_selectedpart == 'N')) ? 0xFF : 0x7F)); // white knight
688
      Render_DrawSprite (&sprites[theme->flatsprites[COLOR_WHITE][PART_BISHOP]],     3.0f * PARTSIZE_PCT, 0, PARTSIZE_PCT, 11.0f, (((scene->gui.partspick_hoveredpart == 'B') || (scene->gui.partspick_selectedpart == 'B')) ? 0xFF : 0x7F)); // white bishop
689
      Render_DrawSprite (&sprites[theme->flatsprites[COLOR_WHITE][PART_QUEEN]],      4.0f * PARTSIZE_PCT, 0, PARTSIZE_PCT, 11.0f, (((scene->gui.partspick_hoveredpart == 'Q') || (scene->gui.partspick_selectedpart == 'Q')) ? 0xFF : 0x7F)); // white queen
690
      Render_DrawSprite (&sprites[theme->flatsprites[COLOR_WHITE][PART_KING]],       5.0f * PARTSIZE_PCT, 0, PARTSIZE_PCT, 11.0f, (((scene->gui.partspick_hoveredpart == 'K') || (scene->gui.partspick_selectedpart == 'K')) ? 0xFF : 0x7F)); // white king
691
      Render_DrawSprite (&sprites[theme->lastmovesource_spriteindex],         6.0f * PARTSIZE_PCT, 0, PARTSIZE_PCT, 11.0f, (((scene->gui.partspick_hoveredpart == ' ') || (scene->gui.partspick_selectedpart == ' ')) ? 0xFF : 0x7F)); // erase mark
692
      Render_DrawSprite (&sprites[theme->flatsprites[COLOR_BLACK][PART_KING]],       7.0f * PARTSIZE_PCT, 0, PARTSIZE_PCT, 11.0f, (((scene->gui.partspick_hoveredpart == 'k') || (scene->gui.partspick_selectedpart == 'k')) ? 0xFF : 0x7F)); // black king
693
      Render_DrawSprite (&sprites[theme->flatsprites[COLOR_BLACK][PART_QUEEN]],      8.0f * PARTSIZE_PCT, 0, PARTSIZE_PCT, 11.0f, (((scene->gui.partspick_hoveredpart == 'q') || (scene->gui.partspick_selectedpart == 'q')) ? 0xFF : 0x7F)); // black queen
694
      Render_DrawSprite (&sprites[theme->flatsprites[COLOR_BLACK][PART_BISHOP]],     9.0f * PARTSIZE_PCT, 0, PARTSIZE_PCT, 11.0f, (((scene->gui.partspick_hoveredpart == 'b') || (scene->gui.partspick_selectedpart == 'b')) ? 0xFF : 0x7F)); // black bishop
695
      Render_DrawSprite (&sprites[theme->flatsprites[COLOR_BLACK][PART_KNIGHT]],    10.0f * PARTSIZE_PCT, 0, PARTSIZE_PCT, 11.0f, (((scene->gui.partspick_hoveredpart == 'n') || (scene->gui.partspick_selectedpart == 'n')) ? 0xFF : 0x7F)); // black knight
696
      Render_DrawSprite (&sprites[theme->flatsprites[COLOR_BLACK][PART_ROOK]],      11.0f * PARTSIZE_PCT, 0, PARTSIZE_PCT, 11.0f, (((scene->gui.partspick_hoveredpart == 'r') || (scene->gui.partspick_selectedpart == 'r')) ? 0xFF : 0x7F)); // black rook
697
      Render_DrawSprite (&sprites[theme->flatsprites[COLOR_BLACK][PART_PAWN]],      12.0f * PARTSIZE_PCT, 0, PARTSIZE_PCT, 11.0f, (((scene->gui.partspick_hoveredpart == 'p') || (scene->gui.partspick_selectedpart == 'p')) ? 0xFF : 0x7F)); // black pawn
698
 
699
#undef PARTSIZE_PCT
700
   }
701
 
702
   // draw GUI texts
703
   DRAW_TEXT_IF_NEEDED (scene->gui.comment_text); // move comments
704
   DRAW_TEXT_IF_NEEDED (scene->gui.history_text); // game history
705
   DRAW_TEXT_IF_NEEDED (scene->gui.clock_text); // game clock
706
 
707
   // draw the chatter channels text
708
   Render_GetTextBoundaries (-1, chat_fontindex, L"a", &rect);
709
   combined_height = rect.bottom; // get a string's height
710
 
711
   // cycle through all the chat strings...
712
   ccreply = NULL;
713
   for (cchistory_index = 0; cchistory_index < scene->gui.cchistory_count; cchistory_index++)
714
   {
715
      ccreply = &scene->gui.cchistory[cchistory_index]; // quick access to CC reply
716
      if ((ccreply->text[0] != 0) && (ccreply->arrival_time + 60.0f > current_time))
717
         break; // break at the first one that we should display
718
   }
719
 
720
   // have we some to display ?
721
   if (cchistory_index < scene->gui.cchistory_count)
722
   {
723
      // first, get the remaining text's combined height
724
      for (cchistory_index2 = cchistory_index; cchistory_index2 < scene->gui.cchistory_count; cchistory_index2++)
725
      {
726
         ccreply = &scene->gui.cchistory[cchistory_index2]; // quick access to CC reply
727
 
728
         combined_width = 10;
729
         Render_GetTextBoundaries (initial_width - combined_width, chat_fontindex, L"[] : ", &rect);
730
         combined_width += rect.right;
731
         Render_GetTextBoundaries (initial_width - combined_width, chat_fontindex, ccreply->channelname, &rect);
732
         combined_width += rect.right;
733
         Render_GetTextBoundaries (initial_width - combined_width, chat_fontindex, ccreply->nickname, &rect);
734
         combined_width += rect.right;
735
         Render_GetTextBoundaries (initial_width - combined_width, chat_fontindex, ccreply->text, &rect);
736
         combined_height += rect.bottom; // add this string's height 
737
      }
738
 
739
      // now for each string remaining...
740
      for (; cchistory_index < scene->gui.cchistory_count; cchistory_index++)
741
      {
742
         ccreply = &scene->gui.cchistory[cchistory_index]; // quick access to CC reply
743
         rect.right = 10;
744
         PRINT_CCREPLY (ccreply); // print CC reply on screen
745
         combined_height -= (rect.bottom - rect.top); // draw it from top of zone to bottom
746
      }
747
   }
748
 
749
   // are we online ?
750
   if (Player_FindByType (PLAYER_INTERNET) != NULL)
751
   {
752
      ccreply = &scene->gui.entered_ccreply;
753
      if (!scene->gui.is_entering_text)
754
         ccreply->color = RGBACOLOR_SETALPHA (ccreply->color, RGBACOLOR_ALPHA (ccreply->color) / 6); // if there's no text being entered, fade CC reply a lot
755
 
756
      rect.right = 10;
757
      PRINT_CCREPLY (ccreply); // print CC reply on screen
758
   }
759
 
760
   // print GUI texts
761
   DRAW_TEXT_IF_NEEDED (scene->gui.turn_text); // player turn's text
762
   DRAW_TEXT_IF_NEEDED (scene->gui.central_text); // central notification zone text
763
 
764
   // if needed, print the spinning wheel
765
   if (scene->gui.want_spinwheel)
766
      Render_DrawSprite (&sprites[spinner_spriteindex[(int) (10.0f * current_time) % 12]], 47.0f, 46.0f, 6.0f, 8.0f, 255);
767
 
768
   // are we in demo mode ? if so, display the program name as a watermark
769
#ifdef DEMO
770
   Render_wprintf (initial_width / 2, initial_height * 2 / 3, -1, ALIGN_CENTER, ALIGN_CENTER, ALIGN_CENTER, chat_fontindex,
771
                   D3DCOLOR_RGBA (255, 255, 255, 191),
772
                   NULL, PROGRAM_NAME L" - " PROGRAM_URL L"\n- %d:%02d -", (int) (DEMO_TIMEOUT - current_time) / 60, (int) (DEMO_TIMEOUT - current_time) % 60);
773
#endif // DEMO
774
 
775
   // end 3D rendering on the back buffer
776
   //////////////////////////////////////
777
 
778
   d3ddev->EndScene (); // ends the 3D scene
779
   d3ddev->Present (NULL, NULL, NULL, NULL); // displays the created frame on the screen
780
 
781
   // update the frame rate
782
   if (framerate_time < current_time)
783
   {
784
      framerate_value = framerate_count;
785
      framerate_count = 0;
786
      framerate_time = current_time + 1.0f;
787
   }
788
   framerate_count++; // one frame more elapsed
789
 
790
   return; // finished
791
}
792
 
793
 
794
int Render_LoadMesh (const wchar_t *fmt, ...)
795
{
796
   // this function appends a new mesh in the global meshes buffer and returns its index
797
 
798
   static wchar_t meshfile_pathname[MAX_PATH];
799
   unsigned long hash;
800
   mesh_t *mesh;
801
   int mesh_index;
802
   va_list argptr;
803
 
804
   // concatenate all the arguments in one string
805
   va_start (argptr, fmt);
806
   wvsprintf (meshfile_pathname, fmt, argptr);
807
   va_end (argptr);
808
 
809
   // resolve wildcards and get content hash
810
   ResolveWildcard (meshfile_pathname, L".obj");
811
   hash = HashFile (meshfile_pathname);
812
 
813
   // now cycle through all our loaded meshes and see if it's already loaded
814
   for (mesh_index = 0; mesh_index < mesh_count; mesh_index++)
815
      if (meshes[mesh_index].hash == hash)
816
         return (mesh_index); // if we can find it, return its index so as not to load it twice
817
 
818
   // reallocate space to hold one mesh more
819
   meshes = (mesh_t *) SAFE_realloc (meshes, mesh_count, mesh_count + 1, sizeof (mesh_t), false);
820
   mesh = &meshes[mesh_count]; // quick access to the mesh we'll be working on
821
 
822
   // load the mesh
823
   if (!Render_LoadMesh_Obj (mesh, meshfile_pathname))
824
   {
825
      MessageBox (NULL, LOCALIZE (L"Error_UnableToAddMeshD3DXLoadMeshFromXFailed"), LOCALIZE (L"FatalError"), MB_ICONERROR | MB_OK);
826
      return (-1); // bomb out on error
827
   }
828
 
829
   mesh->hash = hash; // save the hash
830
   mesh_count++; // we know now one mesh more
831
   return (mesh_count - 1); // return its index
832
}
833
 
834
 
835
int Render_LoadTexture (const wchar_t *fmt, ...)
836
{
837
   // this function appends a new texture in the global textures buffer and returns its index
838
 
839
   D3DSURFACE_DESC texture_description;
840
   wchar_t texturefile_pathname[MAX_PATH];
841
   static wchar_t *filename;
842
   unsigned long hash;
843
   int texture_index;
844
   va_list argptr;
845
 
846
   // concatenate all the arguments in one string
847
   va_start (argptr, fmt);
848
   wvsprintf (texturefile_pathname, fmt, argptr);
849
   va_end (argptr);
850
 
851
   // resolve wildcards and get content hash
852
   ResolveWildcard (texturefile_pathname, L".dds|.jpg|.jpeg|.png|.tga|.bmp");
853
   hash = HashFile (texturefile_pathname);
854
 
855
   // now cycle through all our loaded textures and see if it's already loaded
856
   for (texture_index = 0; texture_index < texture_count; texture_index++)
857
      if (textures[texture_index].hash == hash)
858
         return (texture_index); // if we can find it, return its index so as not to load it twice
859
 
860
   // reallocate space to hold one texture more
861
   textures = (texture_t *) SAFE_realloc (textures, texture_count, texture_count + 1, sizeof (texture_t), false);
862
 
863
   // ask Direct3D to prepare texture data
864
   if (FAILED (D3DXCreateTextureFromFile (d3ddev, texturefile_pathname, &textures[texture_count].texture)))
865
   {
866
      MessageBox (NULL, LOCALIZE (L"Error_UnableToAddTextureD3DXCreateTextureFromFileFailed"), LOCALIZE (L"FatalError"), MB_ICONERROR | MB_OK);
867
      return (-1); // bomb out on error
868
   }
869
 
870
   // get info on the newly loaded texture such as size etc.
871
   textures[texture_count].texture->GetLevelDesc (0, &texture_description);
872
   textures[texture_count].width = texture_description.Width; // save texture width (as loaded)
873
   textures[texture_count].height = texture_description.Height; // save texture height (as loaded)
874
   textures[texture_count].hash = hash; // save its hash
875
   texture_count++; // we know now one texture more
876
   return (texture_count - 1); // return its index
877
}
878
 
879
 
880
int Render_LoadFont (const wchar_t *font_name, int font_size, bool is_bold, bool is_italic)
881
{
882
   // this function appends a new font in the global fonts buffer and returns its index
883
 
884
   unsigned long pathname_hash;
885
   int font_index;
886
 
887
   // first, get the hash of the requested pathname (include font size and weight parameters)
888
   pathname_hash = HashString (font_name);
889
   pathname_hash += 3 * (unsigned long) font_size + 2 * (unsigned long) is_bold + (unsigned long) is_italic;
890
 
891
   // now cycle through all our loaded fonts and see if it's already loaded
892
   for (font_index = 0; font_index < font_count; font_index++)
893
      if (fonts[font_index].pathname_hash == pathname_hash)
894
         return (font_index); // if we can find it, return its index so as not to load it twice
895
 
896
   // reallocate space to hold one font more
897
   fonts = (font_t *) SAFE_realloc (fonts, font_count, font_count + 1, sizeof (font_t), false);
898
 
899
   // create a Direct3D font object and record font data
900
   if (FAILED (D3DXCreateFont (d3ddev, font_size, // font height
901
                               0, // font width
902
                               (is_bold ? FW_BOLD : FW_NORMAL), // font weight (bold, etc)
903
                               0, // miplevels
904
                               is_italic, // is italic
905
                               DEFAULT_CHARSET, // charset
906
                               OUT_DEFAULT_PRECIS, // precision
907
                               CLEARTYPE_QUALITY, // font quality (antialiased or not)
908
                               DEFAULT_PITCH | FF_DONTCARE, // font family
909
                               font_name, // font name
910
                               &fonts[font_count].font))) // and a pointer that will receive the font
911
   {
912
      MessageBox (NULL, LOCALIZE (L"Error_UnableToAddFontD3DXCreateFontFailed"), LOCALIZE (L"FatalError"), MB_ICONERROR | MB_OK);
913
      return (-1); // bomb out on error
914
   }
915
 
916
   fonts[font_count].pathname_hash = pathname_hash; // save its hash
917
   font_count++; // we know now one font more
918
   return (font_count - 1); // return its index
919
}
920
 
921
 
922
int Render_LoadSprite (const wchar_t *fmt, ...)
923
{
924
   // this function appends a new sprite in the global sprites buffer and returns its index
925
 
926
   wchar_t spritefile_pathname[MAX_PATH];
927
   unsigned long hash;
928
   int sprite_index;
929
   va_list argptr;
930
 
931
   // concatenate all the arguments in one string
932
   va_start (argptr, fmt);
933
   wvsprintf (spritefile_pathname, fmt, argptr);
934
   va_end (argptr);
935
 
936
   // resolve wildcards and get content hash
937
   ResolveWildcard (spritefile_pathname, L".dds|.jpg|.jpeg|.png|.tga|.bmp");
938
   hash = HashFile (spritefile_pathname);
939
 
940
   // now cycle through all our loaded sprites and see if it's already loaded
941
   for (sprite_index = 0; sprite_index < sprite_count; sprite_index++)
942
      if (sprites[sprite_index].hash == hash)
943
         return (sprite_index); // if we can find it, return its index so as not to load it twice
944
 
945
   // reallocate space to hold one sprite more
946
   sprites = (sprite_t *) SAFE_realloc (sprites, sprite_count, sprite_count + 1, sizeof (sprite_t), false);
947
 
948
   // ask Direct3D to prepare texture data
949
   if (FAILED (D3DXCreateSprite (d3ddev, &sprites[sprite_count].sprite)))
950
   {
951
      MessageBox (NULL, LOCALIZE (L"Error_UnableToAddSpriteD3DXCreateSpriteFailed"), LOCALIZE (L"FatalError"), MB_ICONERROR | MB_OK);
952
      return (-1); // bomb out on error
953
   }
954
   sprites[sprite_count].texture_index = Render_LoadTexture (spritefile_pathname); // register and save sprite texture
955
   sprites[sprite_count].hash = hash; // save its hash
956
 
957
   sprite_count++; // we know now one sprite more
958
   return (sprite_count - 1); // return its index
959
}
960
 
961
 
962
int Render_MaterialIndexOf (const wchar_t *material_name)
963
{
964
   // this function returns the index of the material in the global materials array which has the specified name
965
 
966
   int material_index;
967
 
968
   // cycle through all materials and look whether one with the specified name exists
969
   for (material_index = 0; material_index < material_count; material_index++)
970
      if (_wcsicmp (materials[material_index].name, material_name) == 0)
971
         return (material_index); // if we find one, return its index
972
 
973
   return (material_count - 1); // else return the index of the last material in list, which is the default material
974
}
975
 
976
 
977
void Render_MouseToFloor (short mouse_x, short mouse_y, float *floor_x, float *floor_y)
978
{
979
   // this function converts a mouse coordinates into floor coordinates by doing vector
980
   // projection on the floor plane from the eyepoint of the camera
981
 
982
   static D3DXPLANE floor_plane;
983
   static bool is_planefound = false;
984
 
985
   D3DXMATRIX projection_matrix;
986
   D3DXMATRIX view_matrix;
987
   D3DXMATRIX invertedview_matrix;
988
   float mouse_pitch;
989
   float mouse_yaw;
990
   vector_t v_lookat;
991
   vector_t v_intersection;
992
 
993
   // find the floor plane (only do it once)
994
   if (!is_planefound)
995
   {
996
      D3DXPlaneFromPointNormal (&floor_plane, (D3DXVECTOR3 *) &scene_center, (D3DXVECTOR3 *) &upwards_direction);
997
      is_planefound = true; // once and for all, as this plane will never change
998
   }
999
 
1000
   // get the current projection and view matrices, and invert the view matrix
1001
   d3ddev->GetTransform (D3DTS_PROJECTION, &projection_matrix);
1002
   d3ddev->GetTransform (D3DTS_VIEW, &view_matrix);
1003
   D3DXMatrixInverse (&invertedview_matrix, NULL, &view_matrix);
1004
 
1005
   // convert the mouse coordinates to relative pitch and yaw
1006
   mouse_pitch =  (((mouse_x * 2.0f) / current_width) - 1) / projection_matrix._11;
1007
   mouse_yaw = -(((mouse_y * 2.0f) / current_height) - 1) / projection_matrix._22;
1008
 
1009
   // now build a matrix that will describe the mouse direction vector, add it to the camera position, and make it 200 times longer
1010
   v_lookat.x = camera_position.x + (mouse_pitch * invertedview_matrix._11 + mouse_yaw * invertedview_matrix._21 + invertedview_matrix._31) * 200.0f;
1011
   v_lookat.y = camera_position.y + (mouse_pitch * invertedview_matrix._12 + mouse_yaw * invertedview_matrix._22 + invertedview_matrix._32) * 200.0f;
1012
   v_lookat.z = camera_position.z + (mouse_pitch * invertedview_matrix._13 + mouse_yaw * invertedview_matrix._23 + invertedview_matrix._33) * 200.0f;
1013
 
1014
   // and the intersection point with our ray
1015
   D3DXPlaneIntersectLine ((D3DXVECTOR3 *) &v_intersection, &floor_plane, (D3DXVECTOR3 *) &camera_position, (D3DXVECTOR3 *) &v_lookat);
1016
 
1017
   // now fill the return values
1018
   *floor_x = v_intersection.x;
1019
   *floor_y = v_intersection.y;
1020
 
1021
   return; // finished
1022
}
1023
 
1024
 
1025
bool Render_IsMouseInBox (short mouse_x, short mouse_y, float x_percent, float y_percent, float width_percent, float height_percent)
1026
{
1027
   // helper function that returns whether the mouse coordinates are inside a given square
1028
 
1029
   float mousex_percent;
1030
   float mousey_percent;
1031
 
1032
   // compute mouse coordinates in percents
1033
   mousex_percent = (float) (mouse_x * 100) / current_width;
1034
   mousey_percent = (float) (mouse_y * 100) / current_height;
1035
 
1036
   return ((mousex_percent >= x_percent) && (mousex_percent <= x_percent + width_percent)
1037
           && (mousey_percent >= y_percent) && (mousey_percent <= y_percent + height_percent));
1038
}
1039
 
1040
 
1041
static bool Render_LoadMesh_Obj (mesh_t *mesh, const wchar_t *objfile_pathname)
1042
{
1043
   // this function loads a mesh from a Wavefront Object file (.obj)
1044
 
1045
   #define OBJ_INCREASE_OR_RESIZE(count,maxcount,increment,arrayptr,type,erase) { \
1046
      (count)++; \
1047
      if ((count) == (maxcount)) \
1048
      { \
1049
         (arrayptr) = (type *) SAFE_realloc ((arrayptr), (maxcount), (maxcount) + (increment), sizeof (type), erase); \
1050
         (maxcount) += (increment); \
1051
      } \
1052
   }
1053
   #define OBJ_CONVERT_INDEX(element,current_element_count) if ((element) < 0) (element) = (current_element_count) + (element); else (element)--;
1054
   #define OBJ_GET_EXISTING_INDEX_OR_APPEND_VERTEX(uniquevertex) \
1055
   { \
1056
      hash = &hashtable[*((unsigned long *) &obj.vs[(uniquevertex).iv].x) & 0xFF]; \
1057
      for (vertex_index = 0; vertex_index < hash->count; vertex_index++) \
1058
         if ((memcmp (&vertices[hash->indices[vertex_index]].position, &obj.vs[(uniquevertex).iv], sizeof (vector_t)) == 0) \
1059
             && (memcmp (&vertices[hash->indices[vertex_index]].normal, &obj.ns[(uniquevertex).in], sizeof (vector_t)) == 0) \
1060
             && (memcmp (&vertices[hash->indices[vertex_index]].texcoord, &obj.tcs[(uniquevertex).itc], sizeof (texcoord_t)) == 0)) \
1061
            break; \
1062
      if (vertex_index == hash->count) \
1063
      { \
1064
         vertex_index = mesh->vertice_count; \
1065
         current_vertex = &vertices[vertex_index]; \
1066
         memset (current_vertex, 0, sizeof (vertex_t)); \
1067
         memcpy (&current_vertex->position, &obj.vs[(uniquevertex).iv], sizeof (vector_t)); \
1068
         if ((uniquevertex).in > -1) \
1069
            memcpy (&current_vertex->normal, &obj.ns[(uniquevertex).in], sizeof (vector_t)); \
1070
         if ((uniquevertex).itc > -1) \
1071
            memcpy (&current_vertex->texcoord, &obj.tcs[(uniquevertex).itc], sizeof (texcoord_t)); \
1072
         hash = &hashtable[*((unsigned long *) &current_vertex->normal.x) & 0xFF]; \
1073
         hash->indices = (long *) SAFE_realloc (hash->indices, hash->count, hash->count + 1, sizeof (long), false); \
1074
         hash->indices[hash->count] = vertex_index; \
1075
         hash->count++; \
1076
         mesh->vertice_count++; \
1077
      } \
1078
      else \
1079
         vertex_index = hash->indices[vertex_index]; \
1080
   }
1081
 
1082
   typedef struct obj_uniquevertex_s { long iv, in, itc; } obj_uniquevertex_t;
1083
   typedef struct obj_face_s { obj_uniquevertex_t v1, v2, v3; } obj_face_t;
1084
   typedef struct obj_hashbucket_s { int count; long *indices; /* mallocated */ } obj_hashbucket_t;
1085
   typedef struct objfile_s
1086
   {
1087
      vector_t *vs; long v_count; long v_maxcount; // array mallocated to v_maxcount
1088
      vector_t *ns; long n_count; long n_maxcount; // array mallocated to n_maxcount
1089
      texcoord_t *tcs; long tc_count; long tc_maxcount; // array mallocated to tc_maxcount
1090
      obj_face_t *fs; long f_count; long f_maxcount; // array mallocated to f_maxcount
1091
   } objfile_t;
1092
 
1093
   static obj_hashbucket_t hashtable[256];
1094
   objfile_t obj;
1095
   obj_hashbucket_t *hash;
1096
   obj_face_t *f;
1097
   vertex_t *vertices; // mallocated
1098
   unsigned long *indices; // mallocated
1099
   vertex_t *current_vertex;
1100
   struct _stat fileinfo;
1101
   char *filedata; // mallocated
1102
   char *fileptr;
1103
   int vertex_index;
1104
   int array_index;
1105
   void *ptr_to;
1106
   FILE *fp;
1107
 
1108
   // open the mesh file and read it as a whole
1109
   _wstat (objfile_pathname, &fileinfo);
1110
   _wfopen_s (&fp, objfile_pathname, L"rb");
1111
   if (fp == NULL)
1112
      return (false); // bomb out on error
1113
   filedata = (char *) SAFE_malloc (fileinfo.st_size, sizeof (char), false); // mallocate space for data
1114
   fread (filedata, fileinfo.st_size, 1, fp); // read file as a whole
1115
   fclose (fp); // file is read, close it
1116
 
1117
   // allocate space for an arbitrary amount of vertices, texture coordinates, normals and faces
1118
   memset (&obj, 0, sizeof (obj));
1119
   obj.v_maxcount = 10000; obj.vs = (vector_t *) SAFE_malloc (obj.v_maxcount, sizeof (vector_t), false);
1120
   obj.n_maxcount = 10000; obj.ns = (vector_t *) SAFE_malloc (obj.n_maxcount, sizeof (vector_t), false);
1121
   obj.tc_maxcount = 10000; obj.tcs = (texcoord_t *) SAFE_malloc (obj.tc_maxcount, sizeof (texcoord_t), false);
1122
   obj.f_maxcount = 5000; obj.fs = (obj_face_t *) SAFE_malloc (obj.f_maxcount, sizeof (obj_face_t), true); // zero out the faces array (IMPORTANT !)
1123
 
1124
   // read file line per line...
1125
   fileptr = filedata - 1; // start parsing line after line
1126
   while (fileptr != NULL)
1127
   {
1128
      fileptr++; // skip the line feed (or reach the first character, if it's the first pass)
1129
 
1130
      // is it a vertex-related line ?
1131
      if (fileptr[0] == L'v')
1132
      {
1133
         // is it a vertex, a normal or a texture coordinate ?
1134
         if ((fileptr[1] == L' ') && (sscanf_s (&fileptr[2], "%f %f %f", &obj.vs[obj.v_count].x, &obj.vs[obj.v_count].y, &obj.vs[obj.v_count].z) == 3))
1135
            OBJ_INCREASE_OR_RESIZE (obj.v_count, obj.v_maxcount, 10000, obj.vs, vector_t, false) // one vertex more has been read
1136
         else if ((fileptr[1] == L'n') && (sscanf_s (&fileptr[3], "%f %f %f", &obj.ns[obj.n_count].x, &obj.ns[obj.n_count].y, &obj.ns[obj.n_count].z) == 3))
1137
            OBJ_INCREASE_OR_RESIZE (obj.n_count, obj.n_maxcount, 10000, obj.ns, vector_t, false) // one normal more has been read
1138
         else if ((fileptr[1] == L't') && (sscanf_s (&fileptr[3], "%f %f", &obj.tcs[obj.tc_count].u, &obj.tcs[obj.tc_count].v) == 2))
1139
            OBJ_INCREASE_OR_RESIZE (obj.tc_count, obj.tc_maxcount, 10000, obj.tcs, texcoord_t, false) // one texture coordinate more has been read
1140
      }
1141
 
1142
      // else is it a face-related line ?
1143
      else if (fileptr[0] == L'f')
1144
      {
1145
         // get a quick pointer to current face (note: it's been already blanked out by malloc())
1146
         f = &obj.fs[obj.f_count];
1147
 
1148
         // is it a face with normals, a face without normals or a face without normals and texture coordinates ?
1149
         if ((sscanf_s (&fileptr[2], "%d/%d/%d %d/%d/%d %d/%d/%d", &f->v1.iv, &f->v1.itc, &f->v1.in, &f->v2.iv, &f->v2.itc, &f->v2.in, &f->v3.iv, &f->v3.itc, &f->v3.in) == 9)
1150
             || (sscanf_s (&fileptr[2], "%d/%d %d/%d %d/%d", &f->v3.iv, &f->v3.itc, &f->v2.iv, &f->v2.itc, &f->v3.iv, &f->v3.itc) == 6)
1151
             || (sscanf_s (&fileptr[2], "%d %d %d", &f->v3.iv, &f->v2.iv, &f->v3.iv) == 6))
1152
         {
1153
            OBJ_CONVERT_INDEX (f->v1.iv, obj.v_count);
1154
            OBJ_CONVERT_INDEX (f->v1.in, obj.n_count); // if no normal could be read, its index will be converted from 0 to -1
1155
            OBJ_CONVERT_INDEX (f->v1.itc, obj.tc_count); // if no texcoord could be read, its index will be converted from 0 to -1
1156
            OBJ_CONVERT_INDEX (f->v2.iv, obj.v_count);
1157
            OBJ_CONVERT_INDEX (f->v2.in, obj.n_count); // if no normal could be read, its index will be converted from 0 to -1
1158
            OBJ_CONVERT_INDEX (f->v2.itc, obj.tc_count); // if no texcoord could be read, its index will be converted from 0 to -1
1159
            OBJ_CONVERT_INDEX (f->v3.iv, obj.v_count);
1160
            OBJ_CONVERT_INDEX (f->v3.in, obj.n_count); // if no normal could be read, its index will be converted from 0 to -1
1161
            OBJ_CONVERT_INDEX (f->v3.itc, obj.tc_count); // if no texcoord could be read, its index will be converted from 0 to -1
1162
            OBJ_INCREASE_OR_RESIZE (obj.f_count, obj.f_maxcount, 5000, obj.fs, obj_face_t, true) // one face more has been read
1163
         }
1164
      }
1165
 
1166
      fileptr = strchr (fileptr, '\n'); // proceed to next line
1167
   }
1168
 
1169
   // now build our final vertex and index list
1170
   vertices = (vertex_t *) SAFE_malloc (3 * obj.f_count, sizeof (vertex_t), false); // mallocate for the max number of vertices we can have
1171
   indices = (unsigned long *) SAFE_malloc (3 * obj.f_count, sizeof (unsigned long), false); // mallocate for the right amount of indices
1172
 
1173
   // t3h mighty l00p ^^ (builds vertex and index buffers)
1174
   memset (hashtable, 0, sizeof (hashtable)); // wipe out the hashtable
1175
   mesh->vertice_count = 0; // start with an unoptimized list
1176
   for (array_index = 0; array_index < obj.f_count; array_index++)
1177
   {
1178
      f = &obj.fs[array_index]; // quick access to current face
1179
      OBJ_GET_EXISTING_INDEX_OR_APPEND_VERTEX (f->v1);
1180
      indices[3 * array_index + 0] = vertex_index;
1181
      OBJ_GET_EXISTING_INDEX_OR_APPEND_VERTEX (f->v2);
1182
      indices[3 * array_index + 1] = vertex_index;
1183
      OBJ_GET_EXISTING_INDEX_OR_APPEND_VERTEX (f->v3);
1184
      indices[3 * array_index + 2] = vertex_index;
1185
   }
1186
 
1187
   // now create a correctly-sized DirectX vertex buffer and populate it
1188
   mesh->vertex_format = D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_TEX1;
1189
   mesh->vertice_size = sizeof (vertex_t);
1190
   d3ddev->CreateVertexBuffer (mesh->vertice_count * mesh->vertice_size, // length
1191
                               D3DUSAGE_DYNAMIC, // usage
1192
                               mesh->vertex_format, // vertex format
1193
                               D3DPOOL_DEFAULT, // pool type
1194
                               &mesh->d3dvertices, // pointer to the vertex buffer pointer
1195
                               NULL); // shared handle
1196
   mesh->d3dvertices->Lock (0, mesh->vertice_count * mesh->vertice_size, &ptr_to, D3DLOCK_DISCARD);
1197
   memcpy (ptr_to, vertices, mesh->vertice_count * mesh->vertice_size);
1198
   mesh->d3dvertices->Unlock ();
1199
 
1200
   // create a correctly-sized DirectX index buffer and populate it
1201
   mesh->is_indexed = true; // remember that we're building an index buffer
1202
   mesh->indice_count = obj.f_count * 3;
1203
   mesh->indice_size = (mesh->indice_count <= (int) USHRT_MAX ? 2 : 4);
1204
   d3ddev->CreateIndexBuffer (mesh->indice_count * mesh->indice_size, // length
1205
                              D3DUSAGE_DYNAMIC, // usage
1206
                              (mesh->indice_size == 2 ? D3DFMT_INDEX16 : D3DFMT_INDEX32), // format (here, 16 or 32-bit)
1207
                              D3DPOOL_DEFAULT, // pool type
1208
                              &mesh->d3dindices, // pointer to the index buffer pointer
1209
                              NULL); // shared handle
1210
   mesh->d3dindices->Lock (0, mesh->indice_count * mesh->indice_size, &ptr_to, D3DLOCK_DISCARD);
1211
   if (mesh->indice_size == 2)
1212
      for (array_index = 0; array_index < mesh->indice_count; array_index++)
1213
         ((unsigned short *) ptr_to)[array_index] = (unsigned short) indices[array_index];
1214
   else
1215
      memcpy (ptr_to, indices, mesh->indice_count * mesh->indice_size);
1216
   mesh->d3dindices->Unlock ();
1217
 
1218
   // finished, free the temporary objects
1219
   for (array_index = 0; array_index < sizeof (hashtable) / sizeof (obj_hashbucket_t); array_index++)
1220
      SAFE_free ((void **) &hashtable[array_index].indices);
1221
   SAFE_free ((void **) &indices);
1222
   SAFE_free ((void **) &vertices);
1223
   SAFE_free ((void **) &obj.vs);
1224
   SAFE_free ((void **) &obj.ns);
1225
   SAFE_free ((void **) &obj.tcs);
1226
   SAFE_free ((void **) &obj.fs);
1227
   SAFE_free ((void **) &filedata);
1228
 
1229
   return (true); // Wavefront Object successfully loaded, return TRUE
1230
 
1231
   #undef OBJ_GET_EXISTING_INDEX_OR_APPEND_VERTEX
1232
   #undef OBJ_CONVERT_INDEX
1233
   #undef OBJ_INCREASE_OR_RESIZE
1234
}
1235
 
1236
 
1237
static void Render_DrawSceneObjectReflection (sceneobject_t *sceneobject)
1238
{
1239
   // fast helper to draw a mesh at a specified location with certain pitch and yaw angles
1240
 
1241
   D3DXMATRIX rotation_matrix;
1242
   D3DXMATRIX translation_matrix;
1243
   D3DXMATRIX reflect_matrix;
1244
   D3DXMATRIX scaling_matrix;
1245
   material_t *material;
1246
   D3DMATERIAL9 d3dmaterial;
1247
   D3DXPLANE plane;
1248
   mesh_t *mesh;
1249
   mesh_t *tile_mesh;
1250
   float alpha;
1251
 
1252
   // draw the reflection below this mesh
1253
 
1254
   // quick access to meshes
1255
   mesh = &meshes[sceneobject->mesh_index];
1256
   tile_mesh = &meshes[theme->tile_meshindex];
1257
 
1258
   // set the world transform at location
1259
   D3DXPlaneFromPointNormal (&plane, (D3DXVECTOR3 *) &scene_center, (D3DXVECTOR3 *) &upwards_direction);
1260
   D3DXMatrixReflect (&reflect_matrix, &plane);
1261
   D3DXMatrixRotationYawPitchRoll (&rotation_matrix, -sceneobject->pitch * TO_RADIANS, 0.0f, -sceneobject->yaw * TO_RADIANS);
1262
   D3DXMatrixTranslation (&translation_matrix, sceneobject->x, sceneobject->y, -sceneobject->z);
1263
   D3DXMatrixScaling (&scaling_matrix, sceneobject->scale, sceneobject->scale, 1.0f);
1264
 
1265
   // tell Direct3D about our matrix
1266
   d3ddev->SetTransform (D3DTS_WORLD, &(reflect_matrix * scaling_matrix * rotation_matrix * translation_matrix));
1267
 
1268
   d3ddev->SetRenderState (D3DRS_STENCILENABLE, true); // enable the stencil buffer
1269
   d3ddev->SetRenderState (D3DRS_STENCILFUNC, D3DCMP_LESS); // instruct how to fill the stencil buffer
1270
   d3ddev->SetRenderState (D3DRS_STENCILPASS, D3DSTENCILOP_KEEP); // instruct how to fill the stencil buffer
1271
 
1272
   // set the texture for this mesh
1273
   if (sceneobject->texture_index != -1)
1274
      d3ddev->SetTexture (0, textures[sceneobject->texture_index].texture);
1275
   else
1276
      d3ddev->SetTexture (0, NULL);
1277
 
1278
   // adjust the light reflection properties by setting the material
1279
   if (sceneobject->material_index != -1)
1280
      material = &materials[sceneobject->material_index]; // use the specified scene object material
1281
   else
1282
      material = &materials[material_count - 1]; // scene object material unspecified, use default material
1283
   alpha = theme->reflection_alpha / 256.0f;
1284
   d3dmaterial.Ambient = D3DXCOLOR (material->ambient, material->ambient, material->ambient, material->transparency * alpha); // Alpha value not used according to SDK
1285
   d3dmaterial.Diffuse = D3DXCOLOR (material->diffuse, material->diffuse, material->diffuse, material->transparency * alpha);
1286
   d3dmaterial.Emissive = D3DXCOLOR (material->emissive, material->emissive, material->emissive, material->transparency * alpha); // Alpha value not used according to SDK
1287
   d3dmaterial.Specular = D3DXCOLOR (material->specular, material->specular, material->specular, material->transparency * alpha); // Alpha value not used according to SDK
1288
   d3dmaterial.Power = material->shininess;
1289
   d3ddev->SetMaterial (&d3dmaterial);
1290
 
1291
   // draw the mesh subset
1292
   d3ddev->SetStreamSource (0, mesh->d3dvertices, 0, sizeof (vertex_t));
1293
   d3ddev->SetFVF (mesh->vertex_format);
1294
   d3ddev->SetRenderState (D3DRS_CULLMODE, D3DCULL_CW); // draw the faces backwards
1295
   if (mesh->is_indexed)
1296
   {
1297
      d3ddev->SetIndices (mesh->d3dindices);
1298
      d3ddev->DrawIndexedPrimitive (D3DPT_TRIANGLELIST, 0, 0, mesh->vertice_count, 0, mesh->indice_count / 3);
1299
   }
1300
   else
1301
      d3ddev->DrawPrimitive (D3DPT_TRIANGLELIST, 0, mesh->vertice_count / 3);
1302
 
1303
   d3ddev->SetRenderState (D3DRS_STENCILENABLE, false); // and disable the stencil buffer
1304
 
1305
   // now draw the simple shadow below this mesh
1306
 
1307
   // grab the tools we need in hand
1308
   d3ddev->SetRenderState (D3DRS_ZENABLE, false); // disable the Z buffer
1309
   d3ddev->SetRenderState (D3DRS_AMBIENT, D3DCOLOR_XRGB (255, 255, 255)); // raise ambient light
1310
 
1311
   // position the simple shadow sprite
1312
   D3DXMatrixScaling (&scaling_matrix, max (sceneobject->simpleshadow_size, sceneobject->z / 5.0f), max (sceneobject->simpleshadow_size, sceneobject->z / 5.0f), 0.0f);
1313
   D3DXMatrixTranslation (&translation_matrix, sceneobject->x, sceneobject->y, 0.0f);
1314
   d3ddev->SetTransform (D3DTS_WORLD, &(scaling_matrix * translation_matrix));
1315
 
1316
   // adjust the light reflection properties by setting the material
1317
   material = &materials[material_count - 1]; // use the default material
1318
   d3dmaterial.Ambient = D3DXCOLOR (material->ambient, material->ambient, material->ambient, material->transparency);
1319
   d3dmaterial.Diffuse = D3DXCOLOR (material->diffuse, material->diffuse, material->diffuse, material->transparency);
1320
   d3dmaterial.Emissive = D3DXCOLOR (material->emissive, material->emissive, material->emissive, material->transparency);
1321
   d3dmaterial.Specular = D3DXCOLOR (material->specular, material->specular, material->specular, material->transparency);
1322
   d3dmaterial.Power = material->shininess;
1323
   d3ddev->SetMaterial (&d3dmaterial);
1324
 
1325
   d3ddev->SetTexture (0, textures[theme->shadow_textureindex].texture); // select the texture we want
1326
 
1327
   // and then draw it
1328
   d3ddev->SetStreamSource (0, tile_mesh->d3dvertices, 0, sizeof (vertex_t)); // set stream source
1329
   d3ddev->SetFVF (tile_mesh->vertex_format); // select which vertex format we are using
1330
   d3ddev->SetRenderState (D3DRS_CULLMODE, D3DCULL_CW); // draw the faces backwards
1331
   if (tile_mesh->is_indexed)
1332
   {
1333
      d3ddev->SetIndices (tile_mesh->d3dindices);
1334
      d3ddev->DrawIndexedPrimitive (D3DPT_TRIANGLELIST, 0, 0, tile_mesh->vertice_count, 0, tile_mesh->indice_count / 3);
1335
   }
1336
   else
1337
      d3ddev->DrawPrimitive (D3DPT_TRIANGLELIST, 0, tile_mesh->vertice_count / 3);
1338
 
1339
   // finished, reset ambient light to its previous value and enable the Z buffer back
1340
   d3ddev->SetRenderState (D3DRS_AMBIENT, ambient_light);
1341
   d3ddev->SetRenderState (D3DRS_ZENABLE, true);
1342
 
1343
   return; // finished
1344
}
1345
 
1346
 
1347
static void Render_DrawSceneObject (sceneobject_t *sceneobject)
1348
{
1349
   // fast helper to draw a mesh at a specified location with certain pitch and yaw angles
1350
 
1351
   D3DXMATRIX rotation_matrix;
1352
   D3DXMATRIX translation_matrix;
1353
   D3DXMATRIX scaling_matrix;
1354
   material_t *material;
1355
   D3DMATERIAL9 d3dmaterial;
1356
   mesh_t *mesh;
1357
 
1358
   // is this object a tile (i.e, it has no mesh) ?
1359
   if (sceneobject->mesh_index == -1)
1360
   {
1361
      Render_DrawSceneTile (sceneobject); // then draw it as a tile instead
1362
      return; // and return
1363
   }
1364
 
1365
   // quick access to mesh
1366
   mesh = &meshes[sceneobject->mesh_index];
1367
 
1368
   // set the world transform at location
1369
   D3DXMatrixRotationYawPitchRoll (&rotation_matrix, sceneobject->pitch * TO_RADIANS, 0.0f, sceneobject->yaw * TO_RADIANS);
1370
   D3DXMatrixTranslation (&translation_matrix, sceneobject->x, sceneobject->y, sceneobject->z);
1371
   D3DXMatrixScaling (&scaling_matrix, sceneobject->scale, sceneobject->scale, 1.0f);
1372
 
1373
   // tell Direct3D about our matrix
1374
   d3ddev->SetTransform (D3DTS_WORLD, &(scaling_matrix * rotation_matrix * translation_matrix));
1375
 
1376
   // set the texture for this mesh
1377
   if (sceneobject->texture_index != -1)
1378
      d3ddev->SetTexture (0, textures[sceneobject->texture_index].texture);
1379
   else
1380
      d3ddev->SetTexture (0, NULL);
1381
 
1382
   // adjust the light reflection properties by setting the material
1383
   if (sceneobject->material_index != -1)
1384
      material = &materials[sceneobject->material_index];
1385
   else
1386
      material = &materials[material_count - 1];
1387
   d3dmaterial.Ambient = D3DXCOLOR (material->ambient, material->ambient, material->ambient, material->transparency);
1388
   d3dmaterial.Diffuse = D3DXCOLOR (material->diffuse, material->diffuse, material->diffuse, material->transparency);
1389
   d3dmaterial.Emissive = D3DXCOLOR (material->emissive, material->emissive, material->emissive, material->transparency);
1390
   d3dmaterial.Specular = D3DXCOLOR (material->specular, material->specular, material->specular, material->transparency);
1391
   d3dmaterial.Power = material->shininess;
1392
   d3ddev->SetMaterial (&d3dmaterial);
1393
 
1394
   // draw the mesh subset
1395
   d3ddev->SetStreamSource (0, mesh->d3dvertices, 0, sizeof (vertex_t));
1396
   d3ddev->SetFVF (mesh->vertex_format);
1397
 
1398
   // is there transparency on this mesh ?
1399
   if (material->transparency < 1)
1400
   {
1401
      d3ddev->SetRenderState (D3DRS_CULLMODE, D3DCULL_CW); // draw the back faces
1402
      if (mesh->is_indexed)
1403
      {
1404
         d3ddev->SetIndices (mesh->d3dindices);
1405
         d3ddev->DrawIndexedPrimitive (D3DPT_TRIANGLELIST, 0, 0, mesh->vertice_count, 0, mesh->indice_count / 3);
1406
      }
1407
      else
1408
         d3ddev->DrawPrimitive (D3DPT_TRIANGLELIST, 0, mesh->vertice_count / 3);
1409
   }
1410
 
1411
   // now draw the front faces
1412
   d3ddev->SetRenderState (D3DRS_CULLMODE, D3DCULL_CCW); // draw the front faces
1413
   if (mesh->is_indexed)
1414
   {
1415
      d3ddev->SetIndices (mesh->d3dindices);
1416
      d3ddev->DrawIndexedPrimitive (D3DPT_TRIANGLELIST, 0, 0, mesh->vertice_count, 0, mesh->indice_count / 3);
1417
   }
1418
   else
1419
      d3ddev->DrawPrimitive (D3DPT_TRIANGLELIST, 0, mesh->vertice_count / 3);
1420
 
1421
   return; // finished
1422
}
1423
 
1424
 
1425
static void Render_DrawSceneTile (sceneobject_t *sceneobject)
1426
{
1427
   // fast helper to draw a tile (i.e, an object that doesn't have a mesh) at a specified location
1428
 
1429
   D3DXMATRIX rotation_matrix;
1430
   D3DXMATRIX translation_matrix;
1431
   D3DXMATRIX scaling_matrix;
1432
   material_t *material;
1433
   D3DMATERIAL9 d3dmaterial;
1434
   mesh_t *tile_mesh;
1435
 
1436
   tile_mesh = &meshes[theme->tile_meshindex]; // quick access to tile mesh
1437
 
1438
   // grab the tools we need in hand
1439
   d3ddev->SetRenderState (D3DRS_AMBIENT, D3DCOLOR_RGBA (0xFF, 0xFF, 0xFF, 0xFF)); // raise light
1440
 
1441
   // set the world transform at location
1442
   D3DXMatrixRotationYawPitchRoll (&rotation_matrix, sceneobject->pitch * TO_RADIANS, 0.0f, sceneobject->yaw * TO_RADIANS);
1443
   D3DXMatrixTranslation (&translation_matrix, sceneobject->x, sceneobject->y, sceneobject->z);
1444
   D3DXMatrixScaling (&scaling_matrix, sceneobject->scale, sceneobject->scale, 1.0f);
1445
 
1446
   // tell Direct3D about our matrix
1447
   d3ddev->SetTransform (D3DTS_WORLD, &(scaling_matrix * rotation_matrix * translation_matrix));
1448
 
1449
   // adjust the light reflection properties by setting the material
1450
   material = &materials[material_count - 1]; // use the default material for tiles
1451
   d3dmaterial.Ambient = D3DXCOLOR (material->ambient, material->ambient, material->ambient, material->ambient);
1452
   d3dmaterial.Diffuse = D3DXCOLOR (material->diffuse, material->diffuse, material->diffuse, material->diffuse);
1453
   d3dmaterial.Emissive = D3DXCOLOR (material->emissive, material->emissive, material->emissive, material->emissive);
1454
   d3dmaterial.Specular = D3DXCOLOR (material->specular, material->specular, material->specular, material->specular);
1455
   d3dmaterial.Power = material->shininess;
1456
   d3ddev->SetMaterial (&d3dmaterial);
1457
 
1458
   // select the texture we want
1459
   d3ddev->SetTexture (0, textures[sceneobject->texture_index].texture);
1460
 
1461
   // and then draw it
1462
   d3ddev->SetStreamSource (0, tile_mesh->d3dvertices, 0, sizeof (vertex_t)); // set stream source
1463
   d3ddev->SetFVF (tile_mesh->vertex_format); // select which vertex format we are using
1464
   d3ddev->SetRenderState (D3DRS_CULLMODE, D3DCULL_CW); // draw the back faces
1465
   if (tile_mesh->is_indexed)
1466
   {
1467
      d3ddev->SetIndices (tile_mesh->d3dindices);
1468
      d3ddev->DrawIndexedPrimitive (D3DPT_TRIANGLELIST, 0, 0, tile_mesh->vertice_count, 0, tile_mesh->indice_count / 3);
1469
   }
1470
   else
1471
      d3ddev->DrawPrimitive (D3DPT_TRIANGLELIST, 0, tile_mesh->vertice_count / 3);
1472
 
1473
   // finished, reset ambient light to its previous value
1474
   d3ddev->SetRenderState (D3DRS_AMBIENT, ambient_light);
1475
 
1476
   return; // finished
1477
}
1478
 
1479
 
1480
static void Render_DrawSprite (sprite_t *sprite, float x_percent, float y_percent, float width_percent, float height_percent, int alpha)
1481
{
1482
   // fast helper to draw a sprite at a specified location with certain parameters
1483
 
1484
   D3DXMATRIX scaling_matrix;
1485
   texture_t *texture;
1486
   float scale_x;
1487
   float scale_y;
1488
 
1489
   texture = &textures[sprite->texture_index]; // quick access to sprite's texture
1490
 
1491
   scale_x = (width_percent * (float) initial_width) / (float) (100 * texture->width);
1492
   scale_y = (height_percent * (float) initial_height) / (float) (100 * texture->height);
1493
 
1494
   // start rendering the sprite (an optimized version would draw all sprites in a row...)
1495
   sprite->sprite->Begin (D3DXSPRITE_ALPHABLEND);
1496
 
1497
   // scale and position the sprite
1498
   D3DXMatrixTransformation2D (&scaling_matrix, // output matrix
1499
                               NULL, // scaling center
1500
                               0.0f, // scaling rotation
1501
                               &D3DXVECTOR2 (scale_x, scale_y), // scaling ratio
1502
                               &D3DXVECTOR2 (0, 0), // rotation center
1503
                               0.0f, // rotation
1504
                               &D3DXVECTOR2 (x_percent * (float) initial_width / 100.0f, y_percent * (float) initial_height / 100.0f)); // translation
1505
   sprite->sprite->SetTransform (&scaling_matrix); // tell the sprite about the scaling and position transform
1506
 
1507
   // now draw the sprite with the specified alpha and finish rendering
1508
   sprite->sprite->Draw (texture->texture, NULL, NULL, NULL, D3DCOLOR_ARGB (alpha, 255, 255, 255));
1509
   sprite->sprite->End ();
1510
 
1511
   return; // finished
1512
}
1513
 
1514
 
1515
static void Render_GetTextBoundaries (int max_width, int font_id, wchar_t *text, RECT *rect)
1516
{
1517
   // this function computes and returns the size of the rectangle the specified text will fit into. Note that text may be modified
1518
   // to insert new lines if it doesn't fit in a single line.
1519
 
1520
   int char_index;
1521
   int length;
1522
   int optimal_length;
1523
   bool have_split;
1524
 
1525
   // blank out the output rectangle
1526
   memset (rect, 0, sizeof (RECT));
1527
 
1528
   // ask direct3D to compute the text size a first time
1529
   fonts[font_id].font->DrawText (NULL, text, -1, rect, DT_CALCRECT, D3DCOLOR (0));
1530
 
1531
   // if max width is not set, set it to viewport width
1532
   if (max_width < 0)
1533
      max_width = initial_width; // then use it to compute the real max width
1534
 
1535
   // do we need more than one line ?
1536
   if (rect->right > max_width)
1537
   {
1538
      // see how many lines we need and compute the optimal length of one line
1539
      length = wcslen (text);
1540
      optimal_length = length / (1 + rect->right / (int) max_width);
1541
      have_split = false;
1542
      for (char_index = optimal_length; char_index < length; char_index++)
1543
         if (iswspace (text[char_index]))
1544
         {
1545
            text[char_index] = L'\n'; // interpolate linefeeds into string
1546
            have_split = true; // remember string has been split
1547
            char_index += optimal_length;
1548
         }
1549
 
1550
      // and ask direct3D to compute the text size again
1551
      fonts[font_id].font->DrawText (NULL, text, -1, rect, DT_CALCRECT, D3DCOLOR (0));
1552
   }
1553
 
1554
   return; // finished
1555
}
1556
 
1557
 
1558
static void Render_wprintf (int x, int y, int max_width, int horiz_align, int vert_align, int text_align, int font_id, unsigned long color_rgba, RECT *out_rect, const wchar_t *fmt, ...)
1559
{
1560
   // this function displays text on the Direct3D interface according to the given parameters. X and Y are the base coordinates of
1561
   // the text's bounding rectangle. Max_width is the maximum allowed width of this rectangle before wrapping words on a new line.
1562
   // Horiz_align and vert_align are the alignment parameters of the RECTANGLE relatively to X and Y. Text_align is the alignment of
1563
   // the TEXT inside this rectangle (meaning, you can have right-aligned text in a rectangle that is centered on a point). Font_id
1564
   // and color.alphargb define the font and color of the text. Out_rect, if filled, will point to a RECT structure describing the text's
1565
   // bounding rectangle, after any word wrapping corrections have been made. Fmt is a format string containing the text itself,
1566
   // printf-style.
1567
 
1568
   va_list argptr;
1569
   RECT rect;
1570
   int left;
1571
   int top;
1572
 
1573
   // concatenate all the arguments in one string
1574
   va_start (argptr, fmt);
1575
   wvsprintf (printf_buffer, fmt, argptr);
1576
   va_end (argptr);
1577
 
1578
   // get the text boundaries
1579
   Render_GetTextBoundaries (max_width, font_id, printf_buffer, &rect);
1580
 
1581
   // horizontal alignment
1582
   if (horiz_align == ALIGN_LEFT)
1583
      left = x;
1584
   else if (horiz_align == ALIGN_RIGHT)
1585
      left = x - rect.right;
1586
   else
1587
      left = x - rect.right / 2;
1588
 
1589
   // vertical alignment
1590
   if (vert_align == ALIGN_TOP)
1591
      top = y;
1592
   else if (vert_align == ALIGN_BOTTOM)
1593
      top = y - rect.bottom;
1594
   else
1595
      top = y - rect.bottom / 2;
1596
 
1597
   // now reposition our rectangle correctly acording to alignment
1598
   OffsetRect (&rect, left, top);
1599
 
1600
   // and draw the text
1601
   if (text_align == ALIGN_LEFT)
1602
      fonts[font_id].font->DrawText (NULL, printf_buffer, -1, &rect, DT_LEFT, RGBACOLOR_TO_ARGBCOLOR (color_rgba));
1603
   else if (horiz_align == ALIGN_RIGHT)
1604
      fonts[font_id].font->DrawText (NULL, printf_buffer, -1, &rect, DT_RIGHT, RGBACOLOR_TO_ARGBCOLOR (color_rgba));
1605
   else
1606
      fonts[font_id].font->DrawText (NULL, printf_buffer, -1, &rect, DT_CENTER, RGBACOLOR_TO_ARGBCOLOR (color_rgba));
1607
 
1608
   // do we want the output rectangle ?
1609
   if (out_rect != NULL)
1610
      memcpy (out_rect, &rect, sizeof (rect)); // if so, copy it in the given variable
1611
 
1612
   return; // finished
1613
}
1614
 
1615
 
1616
static float DistanceToCamera (float x, float y, float z)
1617
{
1618
   // this function computes the distance of the point at coordinates x,y,z to the camera
1619
 
1620
   vector_t displacement;
1621
 
1622
   // compute displacement...
1623
   displacement.x = x - camera_position.x;
1624
   displacement.y = y - camera_position.y;
1625
   displacement.z = z - camera_position.z;
1626
 
1627
   // ...and then Pythagores in 3D
1628
   return (sqrtf (displacement.x * displacement.x + displacement.y * displacement.y + displacement.z * displacement.z));
1629
}
1630
 
1631
 
1632
static float FadeFloat (float from, float to, float start_time, float end_time)
1633
{
1634
   // helper function to return a progressive variation between from and to based on time
1635
 
1636
   if (end_time < current_time)
1637
      return (to);
1638
 
1639
   //      base + (variation) * (               fraction of completion               )
1640
   return (from + (to - from) * (current_time - start_time) / (end_time - start_time));
1641
}
1642
 
1643
 
1644
static unsigned long HashString (const wchar_t *string_buffer)
1645
{
1646
   // super fast string hash function, code courtesy of
1647
   // http://www.azillionmonkeys.com/qed/hash.html
1648
 
1649
   unsigned long length;
1650
   unsigned long hash;
1651
   unsigned long tmp;
1652
   int remaining;
1653
 
1654
   // first, get the string length and start with this as a hash value
1655
   length = wcslen (string_buffer) * sizeof (wchar_t);
1656
   hash = length;
1657
 
1658
   // figure out how many bytes there will remain after 32-bit processing
1659
   remaining = length & 3;
1660
   length >>= 2;
1661
 
1662
   // main loop, process 32-bit blocks
1663
   for ( ; length > 0; length--)
1664
   {
1665
      hash += *((const unsigned short *) string_buffer);
1666
      tmp = ((*((const unsigned short *) (string_buffer + 2))) << 11) ^ hash;
1667
      hash = (hash << 16) ^ tmp;
1668
      string_buffer += 2 * sizeof (unsigned short);
1669
      hash += hash >> 11;
1670
   }
1671
 
1672
   // handle the remaining bytes
1673
   if (remaining == 3)
1674
   {
1675
      hash += *((const unsigned short *) string_buffer);
1676
      hash ^= hash << 16;
1677
      hash ^= string_buffer[sizeof (unsigned short)] << 18;
1678
      hash += hash >> 11;
1679
   }
1680
   else if (remaining == 2)
1681
   {
1682
      hash += *((const unsigned short *) string_buffer);
1683
      hash ^= hash << 11;
1684
      hash += hash >> 17;
1685
   }
1686
   else if (remaining == 1)
1687
   {
1688
      hash += *string_buffer;
1689
      hash ^= hash << 10;
1690
      hash += hash >> 1;
1691
   }
1692
 
1693
   // force "avalanching" of final 127 bits
1694
   hash ^= hash << 3;
1695
   hash += hash >> 5;
1696
   hash ^= hash << 4;
1697
   hash += hash >> 17;
1698
   hash ^= hash << 25;
1699
   hash += hash >> 6;
1700
 
1701
   return (hash); // finished, return the hash value
1702
}
1703
 
1704
 
1705
static unsigned long HashFile (const wchar_t *file_pathname)
1706
{
1707
   // super fast file content pseudo-hash function
1708
 
1709
   unsigned short value;
1710
   struct _stat fileinfo;
1711
   FILE *fp;
1712
 
1713
   // first, get info about the file
1714
   if (_wstat (file_pathname, &fileinfo) != 0)
1715
      return ((unsigned long) time (NULL)); // if file can't be open, return a random number
1716
 
1717
   // open the file
1718
   _wfopen_s (&fp, file_pathname, L"rb");
1719
   if (fp == NULL)
1720
      return ((unsigned long) time (NULL)); // if file can't be open, return a random number
1721
 
1722
   // seek at 2/3 of file size (if file is small enough, return only its content)
1723
   if (fileinfo.st_size >= 4)
1724
   {
1725
      fseek (fp, fileinfo.st_size * 2 / 3, SEEK_SET); // seek at 2/3 of file
1726
      fread (&value, 2, 1, fp); // and read a word here
1727
   }
1728
   else if (fileinfo.st_size >= 2)
1729
      fread (&value, 2, 1, fp);
1730
   else if (fileinfo.st_size == 1)
1731
      value = fgetc (fp);
1732
   else
1733
      value = 0;
1734
 
1735
   // finished, close the file
1736
   fclose (fp);
1737
 
1738
   // and return a hash composed of the 16 lower bits of the file size and the value we read
1739
   return ((unsigned long) (fileinfo.st_size << 16) | (unsigned long) value);
1740
}
1741
 
1742
 
1743
static void ResolveWildcard (wchar_t *file_pathname, wchar_t *extensions_separated_by_bars)
1744
{
1745
   // this function resolves a pathname ending with .* by testing with various possible
1746
   // file extensions until one of the files formed that way is found to exist.
1747
 
1748
   static wchar_t extension_list[256]; // needs to be modifiable for strtok()
1749
   wchar_t *current_extension;
1750
   wchar_t *wcstok_context;
1751
   struct _stat fileinfo;
1752
   int length;
1753
 
1754
   wcscpy_s (extension_list, WCHAR_SIZEOF (extension_list), extensions_separated_by_bars);
1755
   length = wcslen (file_pathname); // get pathname length
1756
 
1757
   // does the pathname we want NOT end with a wildcard ?
1758
   if ((length < 2) || (wcscmp (&file_pathname[length - 2], L".*") != 0))
1759
      return; // no need to resolve anything
1760
 
1761
   // test each extension and see if a corresponding file exists
1762
   current_extension = wcstok_s (extension_list, L"|", &wcstok_context);
1763
   while (current_extension != NULL)
1764
   {
1765
      if (*current_extension == L'.')
1766
         current_extension++; // if current extension starts with a dot, skip it
1767
      wcscpy_s (&file_pathname[length - 1], wcslen (current_extension) + 1, current_extension);
1768
      if (_wstat (file_pathname, &fileinfo) == 0)
1769
         return; // found a file with this extension
1770
      current_extension = wcstok_s (NULL, L"|", &wcstok_context);
1771
   }
1772
 
1773
   wcscpy_s (&file_pathname[length - 1], 2, L"*");
1774
   return; // if none of these extensions match, put the wildcard back and return
1775
}
1776
 
1777
 
1778
static int SortReflectedObjects (const void *object1, const void *object2)
1779
{
1780
   // callback function used by qsort() when sorting the reflected objects according to their distance to the viewer
1781
 
1782
   return ((int) (1000.0f * (((reflectedobject_t *) object2)->distance - ((reflectedobject_t *) object1)->distance)));
1783
}