demoII14_3.cpp
上传用户:husern
上传日期:2018-01-20
资源大小:42486k
文件大小:45k
源码类别:

游戏

开发平台:

Visual C++

  1. // DEMOII14_2.CPP - shadow demo with scaling of the shadow and projection 
  2. // on the ground plane based on actual lightsource position
  3. // READ THIS!
  4. // To compile make sure to include DDRAW.LIB, DSOUND.LIB,
  5. // DINPUT.LIB, DINPUT8.LIB, WINMM.LIB in the project link list, and of course 
  6. // the C++ source modules T3DLIB1-12.CPP and the headers T3DLIB1-12.H
  7. // be in the working directory of the compiler
  8. // INCLUDES ///////////////////////////////////////////////
  9. #define DEBUG_ON
  10. #define INITGUID       // make sure al the COM interfaces are available
  11.                        // instead of this you can include the .LIB file
  12.                        // DXGUID.LIB
  13. #define WIN32_LEAN_AND_MEAN  
  14. #include <windows.h>   // include important windows stuff
  15. #include <windowsx.h> 
  16. #include <mmsystem.h>
  17. #include <iostream.h> // include important C/C++ stuff
  18. #include <conio.h> 
  19. #include <stdlib.h> 
  20. #include <malloc.h> 
  21. #include <memory.h> 
  22. #include <string.h>   
  23. #include <stdarg.h>
  24. #include <stdio.h>    
  25. #include <math.h>
  26. #include <io.h>
  27. #include <fcntl.h>
  28. #include <ddraw.h>  // directX includes 
  29. #include <dsound.h> 
  30. #include <dmksctrl.h>
  31. #include <dmusici.h>
  32. #include <dmusicc.h>
  33. #include <dmusicf.h>
  34. #include <dinput.h> 
  35. #include "T3DLIB1.h" // game library includes
  36. #include "T3DLIB2.h"
  37. #include "T3DLIB3.h"
  38. #include "T3DLIB4.h"
  39. #include "T3DLIB5.h"
  40. #include "T3DLIB6.h"
  41. #include "T3DLIB7.h"
  42. #include "T3DLIB8.h"
  43. #include "T3DLIB9.h"
  44. #include "T3DLIB10.h"
  45. #include "T3DLIB11.h"
  46. #include "T3DLIB12.h"
  47.                                  
  48. // DEFINES ////////////////////////////////////////////////
  49. // defines for windows interface
  50. #define WINDOW_CLASS_NAME "WIN3DCLASS"  // class name
  51. #define WINDOW_TITLE      "T3D Graphics Console Ver 2.0"
  52. #define WINDOW_WIDTH      800  // size of window
  53. #define WINDOW_HEIGHT     600
  54. #define WINDOW_BPP        16    // bitdepth of window (8,16,24 etc.)
  55.                                 // note: if windowed and not
  56.                                 // fullscreen then bitdepth must
  57.                                 // be same as system bitdepth
  58.                                 // also if 8-bit the a pallete
  59.                                 // is created and attached
  60.    
  61. #define WINDOWED_APP      0 // 0 not windowed, 1 windowed
  62. // create some constants for ease of access
  63. #define AMBIENT_LIGHT_INDEX   0 // ambient light index
  64. #define INFINITE_LIGHT_INDEX  1 // infinite light index
  65. #define POINT_LIGHT_INDEX     2 // point light index
  66. #define POINT_LIGHT2_INDEX    3 // point light index
  67. // terrain defines
  68. #define TERRAIN_WIDTH         4000
  69. #define TERRAIN_HEIGHT        4000
  70. #define TERRAIN_SCALE         700
  71. #define MAX_SPEED             20
  72. #define PITCH_RETURN_RATE (.33) // how fast the pitch straightens out
  73. #define PITCH_CHANGE_RATE (.02) // the rate that pitch changes relative to height
  74. #define CAM_HEIGHT_SCALER (.3)  // percentage cam height changes relative to height
  75. #define VELOCITY_SCALER (.025)  // rate velocity changes with height
  76. #define CAM_DECEL       (.25)   // deceleration/friction
  77. #define NUM_OBJECTS          3 // number of objects per class
  78. #define NUM_LIGHT_OBJECTS    5 // number of light models
  79. // PROTOTYPES /////////////////////////////////////////////
  80. // game console
  81. int Game_Init(void *parms=NULL);
  82. int Game_Shutdown(void *parms=NULL);
  83. int Game_Main(void *parms=NULL);
  84. // GLOBALS ////////////////////////////////////////////////
  85. HWND main_window_handle           = NULL; // save the window handle
  86. HINSTANCE main_instance           = NULL; // save the instance
  87. char buffer[2048];                        // used to print text
  88. // initialize camera position and direction
  89. POINT4D  cam_pos    = {0,500,-400,1};
  90. POINT4D  cam_target = {0,0,0,1};
  91. VECTOR4D cam_dir    = {0,0,0,1};
  92. // all your initialization code goes here...
  93. VECTOR4D vscale={1.0,1.0,1.0,1}, 
  94.          vpos = {0,0,150,1}, 
  95.          vrot = {0,0,0,1};
  96. CAM4DV1         cam;            // the single camera
  97. OBJECT4DV2      obj_terrain;    // the terrain object
  98. OBJECT4DV2_PTR  obj_work;
  99. OBJECT4DV2      obj_array[NUM_OBJECTS]; 
  100. OBJECT4DV2_PTR  obj_light;
  101. OBJECT4DV2      obj_light_array[NUM_LIGHT_OBJECTS];
  102. OBJECT4DV2      shadow_obj; 
  103. // filenames of objects to load
  104. char *object_filenames[NUM_OBJECTS] = {
  105.                                         "earth01.cob",
  106.                                         "sphere_gouraud_textured_02.cob",  
  107.                                         "fire_constant_cube01.cob",
  108.                                       };
  109. int curr_object  = 0;
  110. #define INDEX_RED_LIGHT_INDEX       0
  111. #define INDEX_GREEN_LIGHT_INDEX     1
  112. #define INDEX_BLUE_LIGHT_INDEX      2
  113. #define INDEX_YELLOW_LIGHT_INDEX    3
  114. #define INDEX_WHITE_LIGHT_INDEX     4
  115. // filenames of objects to load
  116. char *object_light_filenames[NUM_LIGHT_OBJECTS] = {
  117.                                             "cube_constant_red_01.cob",
  118.                                             "cube_constant_green_01.cob",  
  119.                                             "cube_constant_blue_01.cob",
  120.                                             "cube_constant_yellow_01.cob",
  121.                                             "cube_constant_white_01.cob",
  122.                                             };
  123. int curr_light_object  = 0;
  124. RENDERLIST4DV2  rend_list;      // the render list
  125. RGBAV1          white,          // general colors 
  126.                 gray, 
  127.                 black, 
  128.                 red, 
  129.                 green, 
  130.                 blue,
  131.                 yellow,
  132.                 orange; 
  133. ZBUFFERV1 zbuffer;   // our little z buffer!
  134. RENDERCONTEXTV1  rc; // the rendering context;
  135. // physical model defines play with these to change the feel of the vehicle
  136. float gravity       = -.40;    // general gravity
  137. float vel_y         = 0;       // the y velocity of camera/jeep
  138. float cam_speed     = 0;       // speed of the camera/jeep
  139. float sea_level     = 50;      // sea level of the simulation
  140. float gclearance    = 125;      // clearance from the camera to the ground
  141. float neutral_pitch = 10;   // the neutral pitch of the camera
  142. // sounds
  143. int wind_sound_id = -1;
  144. // game imagery assets
  145. BOB cockpit;               // the cockpit image
  146. // FUNCTIONS //////////////////////////////////////////////
  147. LRESULT CALLBACK WindowProc(HWND hwnd, 
  148.     UINT msg, 
  149.                             WPARAM wparam, 
  150.                             LPARAM lparam)
  151. {
  152. // this is the main message handler of the system
  153. PAINTSTRUCT ps;    // used in WM_PAINT
  154. HDC hdc;    // handle to a device context
  155. // what is the message 
  156. switch(msg)
  157. {
  158. case WM_CREATE: 
  159.         {
  160. // do initialization stuff here
  161. return(0);
  162. } break;
  163.     case WM_PAINT:
  164.          {
  165.          // start painting
  166.          hdc = BeginPaint(hwnd,&ps);
  167.          // end painting
  168.          EndPaint(hwnd,&ps);
  169.          return(0);
  170.         } break;
  171. case WM_DESTROY: 
  172. {
  173. // kill the application
  174. PostQuitMessage(0);
  175. return(0);
  176. } break;
  177. default:break;
  178.     } // end switch
  179. // process any messages that we didn't take care of 
  180. return (DefWindowProc(hwnd, msg, wparam, lparam));
  181. } // end WinProc
  182. // WINMAIN ////////////////////////////////////////////////
  183. int WINAPI WinMain( HINSTANCE hinstance,
  184. HINSTANCE hprevinstance,
  185. LPSTR lpcmdline,
  186. int ncmdshow)
  187. {
  188. // this is the winmain function
  189. WNDCLASS winclass; // this will hold the class we create
  190. HWND  hwnd; // generic window handle
  191. MSG  msg; // generic message
  192. HDC      hdc;       // generic dc
  193. PAINTSTRUCT ps;     // generic paintstruct
  194. // first fill in the window class stucture
  195. winclass.style = CS_DBLCLKS | CS_OWNDC | 
  196.                           CS_HREDRAW | CS_VREDRAW;
  197. winclass.lpfnWndProc = WindowProc;
  198. winclass.cbClsExtra = 0;
  199. winclass.cbWndExtra = 0;
  200. winclass.hInstance = hinstance;
  201. winclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
  202. winclass.hCursor = LoadCursor(NULL, IDC_ARROW);
  203. winclass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
  204. winclass.lpszMenuName = NULL; 
  205. winclass.lpszClassName = WINDOW_CLASS_NAME;
  206. // register the window class
  207. if (!RegisterClass(&winclass))
  208. return(0);
  209. // create the window, note the test to see if WINDOWED_APP is
  210. // true to select the appropriate window flags
  211. if (!(hwnd = CreateWindow(WINDOW_CLASS_NAME, // class
  212.   WINDOW_TITLE,  // title
  213.   (WINDOWED_APP ? (WS_OVERLAPPED | WS_SYSMENU | WS_CAPTION) : (WS_POPUP | WS_VISIBLE)),
  214.     0,0,    // x,y
  215.   WINDOW_WIDTH,  // width
  216.                           WINDOW_HEIGHT, // height
  217.   NULL,    // handle to parent 
  218.   NULL,    // handle to menu
  219.   hinstance,// instance
  220.   NULL))) // creation parms
  221. return(0);
  222. // save the window handle and instance in a global
  223. main_window_handle = hwnd;
  224. main_instance      = hinstance;
  225. // resize the window so that client is really width x height
  226. if (WINDOWED_APP)
  227. {
  228. // now resize the window, so the client area is the actual size requested
  229. // since there may be borders and controls if this is going to be a windowed app
  230. // if the app is not windowed then it won't matter
  231. RECT window_rect = {0,0,WINDOW_WIDTH-1,WINDOW_HEIGHT-1};
  232. // make the call to adjust window_rect
  233. AdjustWindowRectEx(&window_rect,
  234.      GetWindowStyle(main_window_handle),
  235.      GetMenu(main_window_handle) != NULL,  
  236.      GetWindowExStyle(main_window_handle));
  237. // save the global client offsets, they are needed in DDraw_Flip()
  238. window_client_x0 = -window_rect.left;
  239. window_client_y0 = -window_rect.top;
  240. // now resize the window with a call to MoveWindow()
  241. MoveWindow(main_window_handle,
  242.            0,                                    // x position
  243.            0,                                    // y position
  244.            window_rect.right - window_rect.left, // width
  245.            window_rect.bottom - window_rect.top, // height
  246.            FALSE);
  247. // show the window, so there's no garbage on first render
  248. ShowWindow(main_window_handle, SW_SHOW);
  249. } // end if windowed
  250. // perform all game console specific initialization
  251. Game_Init();
  252. // disable CTRL-ALT_DEL, ALT_TAB, comment this line out 
  253. // if it causes your system to crash
  254. SystemParametersInfo(SPI_SCREENSAVERRUNNING, TRUE, NULL, 0);
  255. // enter main event loop
  256. while(1)
  257. {
  258. if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))
  259. // test if this is a quit
  260.         if (msg.message == WM_QUIT)
  261.            break;
  262. // translate any accelerator keys
  263. TranslateMessage(&msg);
  264. // send the message to the window proc
  265. DispatchMessage(&msg);
  266. } // end if
  267.     
  268.     // main game processing goes here
  269.     Game_Main();
  270. } // end while
  271. // shutdown game and release all resources
  272. Game_Shutdown();
  273. // enable CTRL-ALT_DEL, ALT_TAB, comment this line out 
  274. // if it causes your system to crash
  275. SystemParametersInfo(SPI_SCREENSAVERRUNNING, FALSE, NULL, 0);
  276. // return to Windows like this
  277. return(msg.wParam);
  278. } // end WinMain
  279. // T3D II GAME PROGRAMMING CONSOLE FUNCTIONS ////////////////
  280. int Game_Init(void *parms)
  281. {
  282. // this function is where you do all the initialization 
  283. // for your game
  284. int index; // looping var
  285. // start up DirectDraw (replace the parms as you desire)
  286. DDraw_Init2(WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_BPP, WINDOWED_APP,0);
  287. // initialize directinput
  288. DInput_Init();
  289. // acquire the keyboard 
  290. DInput_Init_Keyboard();
  291. // add calls to acquire other directinput devices here...
  292. // initialize directsound and directmusic
  293. DSound_Init();
  294. DMusic_Init();
  295. // hide the mouse
  296. if (!WINDOWED_APP)
  297.     ShowCursor(FALSE);
  298. // seed random number generator
  299. srand(Start_Clock()); 
  300. Open_Error_File("ERROR.TXT");
  301. // initialize math engine
  302. Build_Sin_Cos_Tables();
  303. // initialize the camera with 90 FOV, normalized coordinates
  304. Init_CAM4DV1(&cam,            // the camera object
  305.              CAM_MODEL_EULER, // the euler model
  306.              &cam_pos,        // initial camera position
  307.              &cam_dir,        // initial camera angles
  308.              &cam_target,     // no target
  309.              10.0,            // near and far clipping planes
  310.              12000.0,
  311.              90.0,            // field of view in degrees
  312.              WINDOW_WIDTH,    // size of final screen viewport
  313.              WINDOW_HEIGHT);
  314. VECTOR4D terrain_pos = {0,0,0,0}; 
  315. Generate_Terrain_OBJECT4DV2(&obj_terrain,            // pointer to object
  316.                             TERRAIN_WIDTH,           // width in world coords on x-axis
  317.                             TERRAIN_HEIGHT,          // height (length) in world coords on z-axis
  318.                             TERRAIN_SCALE,           // vertical scale of terrain
  319.                             "height_grass_40_40_01.bmp",  // filename of height bitmap encoded in 256 colors
  320.                             "stone256_256_01.bmp", // "grass256_256_01.bmp", //"checker2562562.bmp",   // filename of texture map
  321.                              RGB16Bit(255,255,255),  // color of terrain if no texture        
  322.                              &terrain_pos,           // initial position
  323.                              NULL,                   // initial rotations
  324.                              POLY4DV2_ATTR_RGB16  
  325.                              //| POLY4DV2_ATTR_SHADE_MODE_FLAT 
  326.                              | POLY4DV2_ATTR_SHADE_MODE_GOURAUD
  327.                              | POLY4DV2_ATTR_SHADE_MODE_TEXTURE);
  328. // set a scaling vector
  329. VECTOR4D_INITXYZ(&vscale, 40, 40, 40);  
  330. // load all the objects in
  331. for (int index_obj=0; index_obj < NUM_OBJECTS; index_obj++)
  332.     {
  333.     Load_OBJECT4DV2_COB2(&obj_array[index_obj], object_filenames[index_obj],  
  334.                         &vscale, &vpos, &vrot, VERTEX_FLAGS_INVERT_WINDING_ORDER 
  335.                                                | VERTEX_FLAGS_TRANSFORM_LOCAL 
  336.                                                | VERTEX_FLAGS_TRANSFORM_LOCAL_WORLD
  337.                                                ,0 );
  338.     // angle for circular rotation
  339.     obj_array[index_obj].ivar1 = 0;
  340.     // set initial position
  341.     obj_array[index_obj].world_pos.x = 0;
  342.     obj_array[index_obj].world_pos.y = 200;
  343.     obj_array[index_obj].world_pos.z = 0;
  344.     
  345.     } // end for index_obj
  346. // set current object
  347. curr_object = 0;
  348. obj_work    = &obj_array[curr_object];
  349. // set a scaling vector
  350. VECTOR4D_INITXYZ(&vscale, 20, 20, 20); 
  351. // load all the light objects in
  352. for (index_obj=0; index_obj < NUM_LIGHT_OBJECTS; index_obj++)
  353.     {
  354.     Load_OBJECT4DV2_COB2(&obj_light_array[index_obj], object_light_filenames[index_obj],  
  355.                         &vscale, &vpos, &vrot, VERTEX_FLAGS_INVERT_WINDING_ORDER 
  356.                                                | VERTEX_FLAGS_TRANSFORM_LOCAL 
  357.                                                | VERTEX_FLAGS_TRANSFORM_LOCAL_WORLD
  358.                                               ,0 );
  359.     } // end for index
  360.    
  361. // set current object
  362. curr_light_object = 0;
  363. obj_light    = &obj_light_array[curr_light_object];
  364. // load the shadow object in
  365. VECTOR4D_INITXYZ(&vscale, 1, 1, 1); 
  366. Load_OBJECT4DV2_COB2(&shadow_obj,"shadow_poly_01.cob",  
  367.                     &vscale, &vpos, &vrot, VERTEX_FLAGS_INVERT_WINDING_ORDER | VERTEX_FLAGS_SWAP_YZ 
  368.                                           | VERTEX_FLAGS_TRANSFORM_LOCAL 
  369.                                           | VERTEX_FLAGS_TRANSFORM_LOCAL_WORLD
  370.                                           ,0 );
  371. // set up lights
  372. Reset_Lights_LIGHTV2(lights2, MAX_LIGHTS);
  373. // create some working colors
  374. white.rgba = _RGBA32BIT(255,255,255,0);
  375. gray.rgba  = _RGBA32BIT(100,100,100,0);
  376. black.rgba = _RGBA32BIT(0,0,0,0);
  377. red.rgba   = _RGBA32BIT(255,0,0,0);
  378. green.rgba = _RGBA32BIT(0,255,0,0);
  379. blue.rgba  = _RGBA32BIT(0,0,255,0);
  380. orange.rgba = _RGBA32BIT(255,128,0,0);
  381. yellow.rgba  = _RGBA32BIT(255,255,0,0);
  382. // ambient light
  383. Init_Light_LIGHTV2(lights2,
  384.                    AMBIENT_LIGHT_INDEX,   
  385.                    LIGHTV2_STATE_ON,      // turn the light on
  386.                    LIGHTV2_ATTR_AMBIENT,  // ambient light type
  387.                    gray, black, black,    // color for ambient term only
  388.                    NULL, NULL,            // no need for pos or dir
  389.                    0,0,0,                 // no need for attenuation
  390.                    0,0,0);                // spotlight info NA
  391. VECTOR4D dlight_dir = {-1,1,-1,1};
  392. // directional light
  393. Init_Light_LIGHTV2(lights2,
  394.                    INFINITE_LIGHT_INDEX,  
  395.                    LIGHTV2_STATE_ON,      // turn the light on
  396.                    LIGHTV2_ATTR_INFINITE, // infinite light type
  397.                    black, gray, black,    // color for diffuse term only
  398.                    NULL, &dlight_dir,     // need direction only
  399.                    0,0,0,                 // no need for attenuation
  400.                    0,0,0);                // spotlight info NA
  401. VECTOR4D plight_pos = {0,500,0,1};
  402. // point light
  403. Init_Light_LIGHTV2(lights2,
  404.                    POINT_LIGHT_INDEX,
  405.                    LIGHTV2_STATE_ON,      // turn the light on
  406.                    LIGHTV2_ATTR_POINT,    // pointlight type
  407.                    black, green, black,   // color for diffuse term only
  408.                    &plight_pos, NULL,     // need pos only
  409.                    0,.001,0,              // linear attenuation only
  410.                    0,0,1);                // spotlight info NA
  411. // point light
  412. Init_Light_LIGHTV2(lights2,
  413.                    POINT_LIGHT2_INDEX,
  414.                    LIGHTV2_STATE_ON,     // turn the light on
  415.                    LIGHTV2_ATTR_POINT,   // pointlight type
  416.                    black, red, black,  // color for diffuse term only
  417.                    &plight_pos, NULL,    // need pos only
  418.                    0,.002,0,             // linear attenuation only
  419.                    0,0,1);               // spotlight info NA
  420. VECTOR4D slight2_pos = {0,200,0,1};
  421. VECTOR4D slight2_dir = {-1,1,-1,1};
  422. // create lookup for lighting engine
  423. RGB_16_8_IndexedRGB_Table_Builder(DD_PIXEL_FORMAT565,  // format we want to build table for
  424.                                   palette,             // source palette
  425.                                   rgblookup);          // lookup table
  426. // create the z buffer
  427. Create_Zbuffer(&zbuffer,
  428.                WINDOW_WIDTH,
  429.                WINDOW_HEIGHT,
  430.                ZBUFFER_ATTR_32BIT);
  431.  
  432. // build alpha lookup table
  433. RGB_Alpha_Table_Builder(NUM_ALPHA_LEVELS, rgb_alpha_table);
  434. // load background sounds
  435. wind_sound_id = DSound_Load_WAV("STATIONTHROB.WAV");
  436. // start the sounds
  437. DSound_Play(wind_sound_id, DSBPLAY_LOOPING);
  438. DSound_Set_Volume(wind_sound_id, 100);
  439. #if 1
  440. // load in the cockpit image
  441. Create_BOB(&cockpit, 0,0,800,600,2, BOB_ATTR_VISIBLE | BOB_ATTR_SINGLE_FRAME, DDSCAPS_SYSTEMMEMORY, 0, 16); 
  442. Load_Bitmap_File(&bitmap16bit, "lego02.BMP");
  443. Load_Frame_BOB16(&cockpit, &bitmap16bit,0,0,0,BITMAP_EXTRACT_MODE_ABS);
  444. Unload_Bitmap_File(&bitmap16bit);
  445. Load_Bitmap_File(&bitmap16bit, "lego02b.BMP");
  446. Load_Frame_BOB16(&cockpit, &bitmap16bit,1,0,0,BITMAP_EXTRACT_MODE_ABS);
  447. Unload_Bitmap_File(&bitmap16bit);
  448. #endif
  449. // set single precission
  450. //_control87( _PC_24, MCW_PC );
  451. // return success
  452. return(1);
  453. } // end Game_Init
  454. ///////////////////////////////////////////////////////////
  455. int Game_Shutdown(void *parms)
  456. {
  457. // this function is where you shutdown your game and
  458. // release all resources that you allocated
  459. // shut everything down
  460. // release all your resources created for the game here....
  461. // now directsound
  462. DSound_Stop_All_Sounds();
  463. DSound_Delete_All_Sounds();
  464. DSound_Shutdown();
  465. // directmusic
  466. DMusic_Delete_All_MIDI();
  467. DMusic_Shutdown();
  468. // shut down directinput
  469. DInput_Release_Keyboard();
  470. // shutdown directinput
  471. DInput_Shutdown();
  472. // shutdown directdraw last
  473. DDraw_Shutdown();
  474. Close_Error_File();
  475. // return success
  476. return(1);
  477. } // end Game_Shutdown
  478. //////////////////////////////////////////////////////////
  479. int Game_Main(void *parms)
  480. {
  481. // this is the workhorse of your game it will be called
  482. // continuously in real-time this is like main() in C
  483. // all the calls for you game go here!
  484. static MATRIX4X4 mrot;   // general rotation matrix
  485. static float plight_ang = 0, 
  486.              slight_ang = 0; // angles for light motion
  487. // use these to rotate objects
  488. static float x_ang = 0, y_ang = 0, z_ang = 0;
  489. // state variables for different rendering modes and help
  490. static int wireframe_mode   = 1;
  491. static int backface_mode    = 1;
  492. static int lighting_mode    = 1;
  493. static int help_mode        = 1;
  494. static int zsort_mode       = 1;
  495. static int x_clip_mode      = 1;
  496. static int y_clip_mode      = 1;
  497. static int z_clip_mode      = 1;
  498. static float hl = 300, // artificial light height
  499.              ks = 1.25; // generic scaling factor to make things look good
  500. char work_string[256]; // temp string
  501. int index; // looping var
  502. // start the timing clock
  503. Start_Clock();
  504. // clear the drawing surface 
  505. DDraw_Fill_Surface(lpddsback, 0);
  506. // draw the sky
  507. Draw_Rectangle(0,0, WINDOW_WIDTH-1, WINDOW_HEIGHT-1, RGB16Bit(50,50,200), lpddsback);
  508. // draw the ground
  509. //Draw_Rectangle(0,WINDOW_HEIGHT*.38, WINDOW_WIDTH, WINDOW_HEIGHT, RGB16Bit(25,50,110), lpddsback);
  510. // read keyboard and other devices here
  511. DInput_Read_Keyboard();
  512. // game logic here...
  513. // reset the render list
  514. Reset_RENDERLIST4DV2(&rend_list);
  515. // modes and lights
  516. // wireframe mode
  517. if (keyboard_state[DIK_W]) 
  518.    {
  519.    // toggle wireframe mode
  520.    if (++wireframe_mode > 1)
  521.        wireframe_mode=0;
  522.    Wait_Clock(100); // wait, so keyboard doesn't bounce
  523.    } // end if
  524. // backface removal
  525. if (keyboard_state[DIK_B])
  526.    {
  527.    // toggle backface removal
  528.    backface_mode = -backface_mode;
  529.    Wait_Clock(100); // wait, so keyboard doesn't bounce
  530.    } // end if
  531. // lighting
  532. if (keyboard_state[DIK_L])
  533.    {
  534.    // toggle lighting engine completely
  535.    lighting_mode = -lighting_mode;
  536.    Wait_Clock(100); // wait, so keyboard doesn't bounce
  537.    } // end if
  538. // toggle ambient light
  539. if (keyboard_state[DIK_A])
  540.    {
  541.    // toggle ambient light
  542.    if (lights2[AMBIENT_LIGHT_INDEX].state == LIGHTV2_STATE_ON)
  543.       lights2[AMBIENT_LIGHT_INDEX].state = LIGHTV2_STATE_OFF;
  544.    else
  545.       lights2[AMBIENT_LIGHT_INDEX].state = LIGHTV2_STATE_ON;
  546.    Wait_Clock(100); // wait, so keyboard doesn't bounce
  547.    } // end if
  548. // toggle infinite light
  549. if (keyboard_state[DIK_I])
  550.    {
  551.    // toggle ambient light
  552.    if (lights2[INFINITE_LIGHT_INDEX].state == LIGHTV2_STATE_ON)
  553.       lights2[INFINITE_LIGHT_INDEX].state = LIGHTV2_STATE_OFF;
  554.    else
  555.       lights2[INFINITE_LIGHT_INDEX].state = LIGHTV2_STATE_ON;
  556.    Wait_Clock(100); // wait, so keyboard doesn't bounce
  557.    } // end if
  558. // toggle point light
  559. if (keyboard_state[DIK_P])
  560.    {
  561.    // toggle point light
  562.    if (lights2[POINT_LIGHT_INDEX].state == LIGHTV2_STATE_ON)
  563.       lights2[POINT_LIGHT_INDEX].state = LIGHTV2_STATE_OFF;
  564.    else
  565.       lights2[POINT_LIGHT_INDEX].state = LIGHTV2_STATE_ON;
  566.    // toggle point light
  567.    if (lights2[POINT_LIGHT2_INDEX].state == LIGHTV2_STATE_ON)
  568.       lights2[POINT_LIGHT2_INDEX].state = LIGHTV2_STATE_OFF;
  569.    else
  570.       lights2[POINT_LIGHT2_INDEX].state = LIGHTV2_STATE_ON;
  571.    Wait_Clock(100); // wait, so keyboard doesn't bounce
  572.    } // end if
  573. // help menu
  574. if (keyboard_state[DIK_H])
  575.    {
  576.    // toggle help menu 
  577.    help_mode = -help_mode;
  578.    Wait_Clock(100); // wait, so keyboard doesn't bounce
  579.    } // end if
  580. // z-sorting
  581. if (keyboard_state[DIK_Z])
  582.    {
  583.    // toggle z sorting
  584.    zsort_mode = -zsort_mode;
  585.    Wait_Clock(100); // wait, so keyboard doesn't bounce
  586.    } // end if
  587. // move to next object
  588. if (keyboard_state[DIK_O])
  589.    {
  590.    VECTOR4D old_pos;
  591.    old_pos = obj_work->world_pos;
  592.    if (++curr_object >= NUM_OBJECTS)
  593.       curr_object = 0;
  594.    // update pointer
  595.    obj_work = &obj_array[curr_object];
  596.    obj_work->world_pos = old_pos;
  597.    Wait_Clock(100); // wait, so keyboard doesn't bounce
  598.    } // end if
  599. // forward/backward
  600. if (keyboard_state[DIK_UP])
  601.    {
  602.    // move forward
  603.    if ( (cam_speed+=1) > MAX_SPEED) cam_speed = MAX_SPEED;
  604.    } // end if
  605. else
  606. if (keyboard_state[DIK_DOWN])
  607.    {
  608.    // move backward
  609.    if ((cam_speed-=1) < -MAX_SPEED) cam_speed = -MAX_SPEED;
  610.    } // end if
  611. // rotate around y axis or yaw
  612. if (keyboard_state[DIK_RIGHT])
  613.    {
  614.    cam.dir.y+=5;
  615.    } // end if
  616. if (keyboard_state[DIK_LEFT])
  617.    {
  618.    cam.dir.y-=5;
  619.    } // end if
  620. // change height of point light source 1
  621. if (keyboard_state[DIK_1])
  622.    {
  623.    lights2[POINT_LIGHT_INDEX].pos.y-=10;
  624.    } // end if
  625. if (keyboard_state[DIK_2])
  626.    {
  627.    lights2[POINT_LIGHT_INDEX].pos.y+=10;
  628.    } // end if
  629. // change height of point light source 2
  630. if (keyboard_state[DIK_3])
  631.    {
  632.    lights2[POINT_LIGHT2_INDEX].pos.y-=10;
  633.    } // end if
  634. if (keyboard_state[DIK_4])
  635.    {
  636.    lights2[POINT_LIGHT2_INDEX].pos.y+=10;
  637.    } // end if
  638. // motion section /////////////////////////////////////////////////////////
  639. // terrain following, simply find the current cell we are over and then
  640. // index into the vertex list and find the 4 vertices that make up the 
  641. // quad cell we are hovering over and then average the values, and based
  642. // on the current height and the height of the terrain push the player upward
  643. // the terrain generates and stores some results to help with terrain following
  644. //ivar1 = columns;
  645. //ivar2 = rows;
  646. //fvar1 = col_vstep;
  647. //fvar2 = row_vstep;
  648. int cell_x = (cam.pos.x  + TERRAIN_WIDTH/2) / obj_terrain.fvar1;
  649. int cell_y = (cam.pos.z  + TERRAIN_HEIGHT/2) / obj_terrain.fvar1;
  650. static float terrain_height, delta;
  651. // test if we are on terrain
  652. if ( (cell_x >=0) && (cell_x < obj_terrain.ivar1) && (cell_y >=0) && (cell_y < obj_terrain.ivar2) )
  653.    {
  654.    // compute vertex indices into vertex list of the current quad
  655.    int v0 = cell_x + cell_y*obj_terrain.ivar2;
  656.    int v1 = v0 + 1;
  657.    int v2 = v1 + obj_terrain.ivar2;
  658.    int v3 = v0 + obj_terrain.ivar2;   
  659.    // now simply index into table 
  660.    terrain_height = 0.25 * (obj_terrain.vlist_trans[v0].y + obj_terrain.vlist_trans[v1].y +
  661.                             obj_terrain.vlist_trans[v2].y + obj_terrain.vlist_trans[v3].y);
  662.    // compute height difference
  663.    delta = terrain_height - (cam.pos.y - gclearance);
  664.    // test for penetration
  665.    if (delta > 0)
  666.       {
  667.       // apply force immediately to camera (this will give it a springy feel)
  668.       vel_y+=(delta * (VELOCITY_SCALER));
  669.       // test for pentration, if so move up immediately so we don't penetrate geometry
  670.       cam.pos.y+=(delta*CAM_HEIGHT_SCALER);
  671.       // now this is more of a hack than the physics model :) let move the front
  672.       // up and down a bit based on the forward velocity and the gradient of the 
  673.       // hill
  674.       cam.dir.x -= (delta*PITCH_CHANGE_RATE);
  675.  
  676.       } // end if
  677.    } // end if
  678. // decelerate camera
  679. if (cam_speed > (CAM_DECEL) ) cam_speed-=CAM_DECEL;
  680. else
  681. if (cam_speed < (-CAM_DECEL) ) cam_speed+=CAM_DECEL;
  682. else
  683.    cam_speed = 0;
  684. // force camera to seek a stable orientation
  685. if (cam.dir.x > (neutral_pitch+PITCH_RETURN_RATE)) cam.dir.x -= (PITCH_RETURN_RATE);
  686. else
  687. if (cam.dir.x < (neutral_pitch-PITCH_RETURN_RATE)) cam.dir.x += (PITCH_RETURN_RATE);
  688.  else 
  689.    cam.dir.x = neutral_pitch;
  690. // apply gravity
  691. vel_y+=gravity;
  692. // test for absolute sea level and push upward..
  693. if (cam.pos.y < sea_level)
  694.    { 
  695.    vel_y = 0; 
  696.    cam.pos.y = sea_level;
  697.    } // end if
  698. // move camera
  699. cam.pos.x += cam_speed*Fast_Sin(cam.dir.y);
  700. cam.pos.z += cam_speed*Fast_Cos(cam.dir.y);
  701. cam.pos.y += vel_y;
  702. // move point light source in ellipse around game world
  703. lights2[POINT_LIGHT_INDEX].pos.x = 500*Fast_Cos(plight_ang);
  704. //lights2[POINT_LIGHT_INDEX].pos.y = 200;
  705. lights2[POINT_LIGHT_INDEX].pos.z = 500*Fast_Sin(plight_ang);
  706. // move point light source in ellipse around game world
  707. lights2[POINT_LIGHT2_INDEX].pos.x = 200*Fast_Cos(-2*plight_ang);
  708. //lights2[POINT_LIGHT2_INDEX].pos.y = 400;
  709. lights2[POINT_LIGHT2_INDEX].pos.z = 200*Fast_Sin(-2*plight_ang);
  710. if ((plight_ang+=1) > 360)
  711.     plight_ang = 0;
  712. // generate camera matrix
  713. Build_CAM4DV1_Matrix_Euler(&cam, CAM_ROT_SEQ_ZYX);
  714. //////////////////////////////////////////////////////////////////////////
  715. // the terrain
  716. // reset the object (this only matters for backface and object removal)
  717. Reset_OBJECT4DV2(&obj_terrain);
  718. // generate rotation matrix around y axis
  719. //Build_XYZ_Rotation_MATRIX4X4(x_ang, y_ang, z_ang, &mrot);
  720. MAT_IDENTITY_4X4(&mrot); 
  721. // rotate the local coords of the object
  722. Transform_OBJECT4DV2(&obj_terrain, &mrot, TRANSFORM_LOCAL_TO_TRANS,1);
  723. // perform world transform
  724. Model_To_World_OBJECT4DV2(&obj_terrain, TRANSFORM_TRANS_ONLY);
  725. // insert the object into render list
  726. Insert_OBJECT4DV2_RENDERLIST4DV2(&rend_list, &obj_terrain,0);
  727. //////////////////////////////////////////////////////////////////////////
  728. //////////////////////////////////////////////////////////////////////////
  729. // shaded object
  730. // reset the object (this only matters for backface and object removal)
  731. Reset_OBJECT4DV2(obj_work);
  732. // set position of object 
  733. // update rotation angle of object
  734. obj_work->ivar1+=1.0;
  735. if (obj_work->ivar1 >= 360)
  736.     obj_work->ivar1 = 0;
  737. obj_work->world_pos.x = 150*Fast_Cos(obj_work->ivar1);
  738. obj_work->world_pos.y = 200+75*Fast_Sin(obj_work->ivar1);
  739. obj_work->world_pos.z = 150*Fast_Sin(obj_work->ivar1);
  740. // generate rotation matrix around y axis
  741. Build_XYZ_Rotation_MATRIX4X4(x_ang, y_ang, z_ang, &mrot);
  742. // rotate the local coords of the object
  743. Transform_OBJECT4DV2(obj_work, &mrot, TRANSFORM_LOCAL_TO_TRANS,1);
  744. // perform world transform
  745. Model_To_World_OBJECT4DV2(obj_work, TRANSFORM_TRANS_ONLY);
  746. // insert the object into render list
  747. Insert_OBJECT4DV2_RENDERLIST4DV2(&rend_list, obj_work,0);
  748. //////////////////////////////////////////////////////////////////////////
  749. //////////////////////////////////////////////////////////////////////////
  750. // draw all the light objects to represent the position of light sources
  751. // reset the object (this only matters for backface and object removal)
  752. Reset_OBJECT4DV2(&obj_light_array[INDEX_GREEN_LIGHT_INDEX]);
  753. // set position of object to light
  754. obj_light_array[INDEX_GREEN_LIGHT_INDEX].world_pos = lights2[POINT_LIGHT_INDEX].pos;
  755. // create identity matrix
  756. MAT_IDENTITY_4X4(&mrot);
  757. // transform the local coords of the object
  758. Transform_OBJECT4DV2(&obj_light_array[INDEX_GREEN_LIGHT_INDEX], &mrot, TRANSFORM_LOCAL_TO_TRANS,1);
  759. // perform world transform
  760. Model_To_World_OBJECT4DV2(&obj_light_array[INDEX_GREEN_LIGHT_INDEX], TRANSFORM_TRANS_ONLY);
  761. // insert the object into render list
  762. Insert_OBJECT4DV2_RENDERLIST4DV2(&rend_list, &obj_light_array[INDEX_GREEN_LIGHT_INDEX],0);
  763. // reset the object (this only matters for backface and object removal)
  764. Reset_OBJECT4DV2(&obj_light_array[INDEX_RED_LIGHT_INDEX]);
  765. // set position of object to light
  766. obj_light_array[INDEX_RED_LIGHT_INDEX].world_pos = lights2[POINT_LIGHT2_INDEX].pos;
  767. // create identity matrix
  768. MAT_IDENTITY_4X4(&mrot);
  769. // transform the local coords of the object
  770. Transform_OBJECT4DV2(&obj_light_array[INDEX_RED_LIGHT_INDEX], &mrot, TRANSFORM_LOCAL_TO_TRANS,1);
  771. // perform world transform
  772. Model_To_World_OBJECT4DV2(&obj_light_array[INDEX_RED_LIGHT_INDEX], TRANSFORM_TRANS_ONLY);
  773. // insert the object into render list
  774. Insert_OBJECT4DV2_RENDERLIST4DV2(&rend_list, &obj_light_array[INDEX_RED_LIGHT_INDEX],0);
  775. ////////////////////////////////////////////////////////////////////////////////////
  776. // reset number of polys rendered
  777. debug_polys_rendered_per_frame = 0;
  778. debug_polys_lit_per_frame = 0;
  779. // perform first rendering pass
  780. // remove backfaces
  781. if (backface_mode==1)
  782.    Remove_Backfaces_RENDERLIST4DV2(&rend_list, &cam);
  783. // apply world to camera transform
  784. World_To_Camera_RENDERLIST4DV2(&rend_list, &cam);
  785. // clip the polygons themselves now
  786. Clip_Polys_RENDERLIST4DV2(&rend_list, &cam, CLIP_POLY_X_PLANE | CLIP_POLY_Y_PLANE | CLIP_POLY_Z_PLANE );
  787. // light scene all at once 
  788. if (lighting_mode==1)
  789.    {
  790.    Transform_LIGHTSV2(lights2, 4, &cam.mcam, TRANSFORM_LOCAL_TO_TRANS);
  791.    Light_RENDERLIST4DV2_World2_16(&rend_list, &cam, lights2, 4);
  792.    } // end if
  793. // sort the polygon list (hurry up!)
  794. if (zsort_mode == 1)
  795.    Sort_RENDERLIST4DV2(&rend_list,  SORT_POLYLIST_AVGZ);
  796. // apply camera to perspective transformation
  797. Camera_To_Perspective_RENDERLIST4DV2(&rend_list, &cam);
  798. // apply screen transform
  799. Perspective_To_Screen_RENDERLIST4DV2(&rend_list, &cam);
  800. // lock the back buffer
  801. DDraw_Lock_Back_Surface();
  802. // reset number of polys rendered
  803. debug_polys_rendered_per_frame = 0;
  804. // render the object
  805. if (wireframe_mode  == 0)
  806.    Draw_RENDERLIST4DV2_Wire16(&rend_list, back_buffer, back_lpitch);
  807. else
  808. if (wireframe_mode  == 1)
  809.    {
  810.    // perspective mode affine texturing
  811.       // set up rendering context
  812.       rc.attr =    RENDER_ATTR_ZBUFFER  
  813.               // | RENDER_ATTR_ALPHA  
  814.               // | RENDER_ATTR_MIPMAP  
  815.               // | RENDER_ATTR_BILERP
  816.                  | RENDER_ATTR_TEXTURE_PERSPECTIVE_AFFINE;
  817.    // initialize zbuffer to 0 fixed point
  818.    Clear_Zbuffer(&zbuffer, (16000 << FIXP16_SHIFT));
  819.    // set up remainder of rendering context
  820.    rc.video_buffer   = back_buffer;
  821.    rc.lpitch         = back_lpitch;
  822.    rc.mip_dist       = 0;
  823.    rc.zbuffer        = (UCHAR *)zbuffer.zbuffer;
  824.    rc.zpitch         = WINDOW_WIDTH*4;
  825.    rc.rend_list      = &rend_list;
  826.    rc.texture_dist   = 0;
  827.    rc.alpha_override = -1;
  828.    // render scene
  829.    Draw_RENDERLIST4DV2_RENDERCONTEXTV1_16_2(&rc);
  830.    } // end if
  831. // now make second rendering pass and draw shadow
  832. // reset the render list
  833. Reset_RENDERLIST4DV2(&rend_list);
  834. // reset shadow image for car, if in shadow change to 0
  835. cockpit.curr_frame = 0;
  836. int v0, v1, v2, v3; // used to track vertices
  837. VECTOR4D pl,  // position of the light
  838.          po,  // position of the occluder object
  839.          vlo, // vector from light to object
  840.          ps;  // position of the shadow
  841. float    rs,  // radius of shadow 
  842.          t;   // parameter t
  843. //////////////////////////////////////////////////////////////////////////
  844. // shadow object
  845. // reset the object (this only matters for backface and object removal)
  846. Reset_OBJECT4DV2(&shadow_obj);
  847. // compute terrain cell shadow is over
  848. cell_x = (obj_work->world_pos.x  + TERRAIN_WIDTH/2) / obj_terrain.fvar1;
  849. cell_y = (obj_work->world_pos.z  + TERRAIN_HEIGHT/2) / obj_terrain.fvar1;
  850. // compute vertex indices into vertex list of the current quad
  851. v0 = cell_x + cell_y*obj_terrain.ivar2;
  852. v1 = v0 + 1;
  853. v2 = v1 + obj_terrain.ivar2;
  854. v3 = v0 + obj_terrain.ivar2;   
  855. // now simply index into table 
  856. terrain_height = MAX(    MAX(obj_terrain.vlist_trans[v0].y, obj_terrain.vlist_trans[v1].y), 
  857.                          MAX(obj_terrain.vlist_trans[v2].y, obj_terrain.vlist_trans[v3].y) );
  858. // update position
  859. //shadow_obj.world_pos   = obj_work->world_pos;
  860. shadow_obj.world_pos.y = terrain_height+25;
  861. // using point light source 1 as the projector, compute target projection
  862. // position, use local variables to make the math easier to understand
  863. // assign light position from point light
  864. pl = lights2[POINT_LIGHT_INDEX].pos;
  865. // assign object position
  866. po = obj_work->world_pos;
  867. // create vector from lightsource to object
  868. VECTOR4D_Build(&pl, &po, &vlo);
  869. // now, comes the fun part, solve for t when y=0 of the projector line
  870. // technically, we are placing the shadow slightly higher in the math above,
  871. // so if you like, you can change the solution of t to take that into consideration
  872. // but this is cleaner for now
  873. t = -pl.y / vlo.y;
  874. // now compute x,z of projected shadow position (scale t by .5 to keep the shadow close)
  875. shadow_obj.world_pos.x = pl.x + t*vlo.x;
  876. shadow_obj.world_pos.z = pl.z + t*vlo.z;
  877. // now compute the size of the shadow radius based on the calculations shown in the book
  878. // the size of the projected shadow, assuming a sphere as the occluder with a point lightsource
  879. // height hl above the ground plane, a spherical object with radius ro, and height above
  880. // the groundplane ho, the radius of the shadow is rs:
  881. //
  882. //    rs = ro * (hl)/(hl - ho)
  883. // set height to altitude of light
  884. hl = lights2[POINT_LIGHT_INDEX].pos.y;
  885. // use the average radius of the object to base calcs on, better than nothing
  886. rs = ks * ( obj_work->avg_radius[0] * (hl/ (hl - obj_work->world_pos.y)) );
  887. // generate scaling matrix bases on shadow scale
  888. MAT_IDENTITY_4X4(&mrot);
  889. // set scaling values to scale in X-Z plane
  890. mrot.M00 = rs;
  891. mrot.M11 = 1.0;
  892. mrot.M22 = rs;
  893. // scale the local coords of the object
  894. Transform_OBJECT4DV2(&shadow_obj, &mrot, TRANSFORM_LOCAL_TO_TRANS,1);
  895. // perform world transform
  896. Model_To_World_OBJECT4DV2(&shadow_obj, TRANSFORM_TRANS_ONLY);
  897. // insert the object into render list
  898. Insert_OBJECT4DV2_RENDERLIST4DV2(&rend_list, &shadow_obj,0);
  899. //////////////////////////////////////////////////////////////////////////
  900. // test if camera is in shadow
  901. VECTOR4D vd;
  902. VECTOR4D_Build(&cam.pos, &shadow_obj.world_pos, &vd);
  903. float d = VECTOR4D_Length_Fast(&vd);
  904. // test if distance is within 1.5 times the radius of the shadow, the 1.5 makes it
  905. // a little more noticeable
  906. if (d < 1.5*rs)
  907.    cockpit.curr_frame = 1; // cockpit with lower brightness
  908. //////////////////////////////////////////////////////////////////////////
  909. // shadow object
  910. // reset the object (this only matters for backface and object removal)
  911. Reset_OBJECT4DV2(&shadow_obj);
  912. // compute terrain cell shadow is over
  913. cell_x = (obj_work->world_pos.x  + TERRAIN_WIDTH/2) / obj_terrain.fvar1;
  914. cell_y = (obj_work->world_pos.z  + TERRAIN_HEIGHT/2) / obj_terrain.fvar1;
  915. // compute vertex indices into vertex list of the current quad
  916. v0 = cell_x + cell_y*obj_terrain.ivar2;
  917. v1 = v0 + 1;
  918. v2 = v1 + obj_terrain.ivar2;
  919. v3 = v0 + obj_terrain.ivar2;   
  920. // now simply index into table 
  921. terrain_height = MAX(    MAX(obj_terrain.vlist_trans[v0].y, obj_terrain.vlist_trans[v1].y), 
  922.                          MAX(obj_terrain.vlist_trans[v2].y, obj_terrain.vlist_trans[v3].y) );
  923. // update position
  924. //shadow_obj.world_pos   = obj_work->world_pos;
  925. shadow_obj.world_pos.y = terrain_height+25;
  926. // using point light source 1 as the projector, compute target projection
  927. // position, use local variables to make the math easier to understand
  928. // assign light position from point light
  929. pl = lights2[POINT_LIGHT2_INDEX].pos;
  930. // assign object position
  931. po = obj_work->world_pos;
  932. // create vector from lightsource to object
  933. VECTOR4D_Build(&pl, &po, &vlo);
  934. // now, comes the fun part, solve for t when y=0 of the projector line
  935. // technically, we are placing the shadow slightly higher in the math above,
  936. // so if you like, you can change the solution of t to take that into consideration
  937. // but this is cleaner for now
  938. t = -pl.y / vlo.y;
  939. // now compute x,z of projected shadow position (scale t by .5 to keep the shadow close)
  940. shadow_obj.world_pos.x = pl.x + t*vlo.x;
  941. shadow_obj.world_pos.z = pl.z + t*vlo.z;
  942. // now compute the size of the shadow radius based on the calculations shown in the book
  943. // the size of the projected shadow, assuming a sphere as the occluder with a point lightsource
  944. // height hl above the ground plane, a spherical object with radius ro, and height above
  945. // the groundplane ho, the radius of the shadow is rs:
  946. //
  947. //    rs = ro * (hl)/(hl - ho)
  948. // set height to altitude of light
  949. hl = lights2[POINT_LIGHT2_INDEX].pos.y;
  950. // use the average radius of the object to base calcs on, better than nothing
  951. rs = ks * ( obj_work->avg_radius[0] * (hl/ (hl - obj_work->world_pos.y)) );
  952. // generate scaling matrix bases on shadow scale
  953. MAT_IDENTITY_4X4(&mrot);
  954. // set scaling values to scale in X-Z plane
  955. mrot.M00 = rs;
  956. mrot.M11 = 1.0;
  957. mrot.M22 = rs;
  958. // scale the local coords of the object
  959. Transform_OBJECT4DV2(&shadow_obj, &mrot, TRANSFORM_LOCAL_TO_TRANS,1);
  960. // perform world transform
  961. Model_To_World_OBJECT4DV2(&shadow_obj, TRANSFORM_TRANS_ONLY);
  962. // insert the object into render list
  963. Insert_OBJECT4DV2_RENDERLIST4DV2(&rend_list, &shadow_obj,0);
  964. //////////////////////////////////////////////////////////////////////////
  965. // test if camera is in shadow
  966. VECTOR4D_Build(&cam.pos, &shadow_obj.world_pos, &vd);
  967. d = VECTOR4D_Length_Fast(&vd);
  968. // test if distance is within 1.5 times the radius of the shadow, the 1.5 makes it
  969. // a little more noticeable
  970. if (d < 1.5*rs)
  971.    cockpit.curr_frame = 1; // cockpit with lower brightness
  972. // remove backfaces
  973. if (backface_mode==1)
  974.    Remove_Backfaces_RENDERLIST4DV2(&rend_list, &cam);
  975. // apply world to camera transform
  976. World_To_Camera_RENDERLIST4DV2(&rend_list, &cam);
  977. // clip the polygons themselves now
  978. Clip_Polys_RENDERLIST4DV2(&rend_list, &cam, CLIP_POLY_X_PLANE | CLIP_POLY_Y_PLANE | CLIP_POLY_Z_PLANE );
  979. // light scene all at once 
  980. if (lighting_mode==1)
  981.    {
  982.    Transform_LIGHTSV2(lights2, 4, &cam.mcam, TRANSFORM_LOCAL_TO_TRANS);
  983.    Light_RENDERLIST4DV2_World2_16(&rend_list, &cam, lights2, 4);
  984.    } // end if
  985. // sort the polygon list (hurry up!)
  986. if (zsort_mode == 1)
  987.    Sort_RENDERLIST4DV2(&rend_list,  SORT_POLYLIST_AVGZ);
  988. // apply camera to perspective transformation
  989. Camera_To_Perspective_RENDERLIST4DV2(&rend_list, &cam);
  990. // apply screen transform
  991. Perspective_To_Screen_RENDERLIST4DV2(&rend_list, &cam);
  992. // render the object
  993. if (wireframe_mode  == 0)
  994.    Draw_RENDERLIST4DV2_Wire16(&rend_list, back_buffer, back_lpitch);
  995. else
  996. if (wireframe_mode  == 1)
  997.    {
  998.    // perspective mode affine texturing
  999.       // set up rendering context
  1000.       rc.attr =    RENDER_ATTR_ZBUFFER  
  1001.                  | RENDER_ATTR_ALPHA  
  1002.               // | RENDER_ATTR_MIPMAP  
  1003.               // | RENDER_ATTR_BILERP
  1004.                  | RENDER_ATTR_TEXTURE_PERSPECTIVE_AFFINE;
  1005.    // initialize zbuffer to 0 fixed point
  1006.    //Clear_Zbuffer(&zbuffer, (16000 << FIXP16_SHIFT));
  1007.    // set up remainder of rendering context
  1008.    rc.video_buffer   = back_buffer;
  1009.    rc.lpitch         = back_lpitch;
  1010.    rc.mip_dist       = 0;
  1011.    rc.zbuffer        = (UCHAR *)zbuffer.zbuffer;
  1012.    rc.zpitch         = WINDOW_WIDTH*4;
  1013.    rc.rend_list      = &rend_list;
  1014.    rc.texture_dist   = 0;
  1015.    rc.alpha_override = -1;
  1016.    // render scene
  1017.    Draw_RENDERLIST4DV2_RENDERCONTEXTV1_16_3(&rc);
  1018.    } // end if
  1019. // unlock the back buffer
  1020. DDraw_Unlock_Back_Surface();
  1021. // draw cockpit
  1022. Draw_BOB16(&cockpit, lpddsback);
  1023. sprintf(work_string,"Lighting [%s]: Ambient=%d, Infinite=%d, Point=%d, BckFceRM [%s], Green Light y=%f, Red Light y=%f", 
  1024.                                                                                  ((lighting_mode == 1) ? "ON" : "OFF"),
  1025.                                                                                  lights2[AMBIENT_LIGHT_INDEX].state,
  1026.                                                                                  lights2[INFINITE_LIGHT_INDEX].state, 
  1027.                                                                                  lights2[POINT_LIGHT_INDEX].state,
  1028.                                                                                  ((backface_mode == 1) ? "ON" : "OFF"), 
  1029.                                                                                  lights2[POINT_LIGHT_INDEX].pos.y, lights2[POINT_LIGHT2_INDEX].pos.y);
  1030. Draw_Text_GDI(work_string, 0, WINDOW_HEIGHT-34, RGB(0,255,0), lpddsback);
  1031. // draw instructions
  1032. Draw_Text_GDI("Press ESC to exit. Press <H> for Help.", 0, 0, RGB(0,255,0), lpddsback);
  1033. // should we display help
  1034. int text_y = 16; 
  1035. if (help_mode==1)
  1036.     {
  1037.     // draw help menu
  1038.     Draw_Text_GDI("<A>..............Toggle ambient light source.", 0, text_y+=12, RGB(255,255,255), lpddsback);
  1039.     Draw_Text_GDI("<I>..............Toggle infinite light source.", 0, text_y+=12, RGB(255,255,255), lpddsback);
  1040.     Draw_Text_GDI("<P>..............Toggle point light source.", 0, text_y+=12, RGB(255,255,255), lpddsback);
  1041.     Draw_Text_GDI("<W>..............Toggle wire frame/solid mode.", 0, text_y+=12, RGB(255,255,255), lpddsback);
  1042.     Draw_Text_GDI("<B>..............Toggle backface removal.", 0, text_y+=12, RGB(255,255,255), lpddsback);
  1043.     Draw_Text_GDI("<O>..............Select different objects.", 0, text_y+=12, RGB(255,255,255), lpddsback);
  1044.     Draw_Text_GDI("<1>,<2>..........Change height of green point light.", 0, text_y+=12, RGB(255,255,255), lpddsback);
  1045.     Draw_Text_GDI("<3>,<4>..........Change height of red point light.", 0, text_y+=12, RGB(255,255,255), lpddsback);
  1046.     Draw_Text_GDI("<H>..............Toggle Help.", 0, text_y+=12, RGB(255,255,255), lpddsback);
  1047.     Draw_Text_GDI("<ESC>............Exit demo.", 0, text_y+=12, RGB(255,255,255), lpddsback);
  1048.     } // end help
  1049. sprintf(work_string,"Polys Rendered: %d, Polys lit: %d", debug_polys_rendered_per_frame, debug_polys_lit_per_frame);
  1050. Draw_Text_GDI(work_string, 0, WINDOW_HEIGHT-34-16-16, RGB(0,255,0), lpddsback);
  1051. sprintf(work_string,"CAM [%5.2f, %5.2f, %5.2f], CELL [%d, %d]",  cam.pos.x, cam.pos.y, cam.pos.z, cell_x, cell_y);
  1052. Draw_Text_GDI(work_string, 0, WINDOW_HEIGHT-34-16-16-16, RGB(0,255,0), lpddsback);
  1053. // flip the surfaces
  1054. DDraw_Flip2();
  1055. // sync to 30ish fps
  1056. Wait_Clock(30);
  1057. // check of user is trying to exit
  1058. if (KEY_DOWN(VK_ESCAPE) || keyboard_state[DIK_ESCAPE])
  1059.     {
  1060.     PostMessage(main_window_handle, WM_DESTROY,0,0);
  1061.     } // end if
  1062. // return success
  1063. return(1);
  1064.  
  1065. } // end Game_Main
  1066. //////////////////////////////////////////////////////////